public ActionResult Create(Post post)
        {
            // verify that provided model is valid
            if (ModelState.IsValid)
            {
                // pull username from stored cookie
                post.Username = User.Identity.Name;

                // add timestamp to post
                post.Timestamp = DateTime.Now;

                // store new Post record into Posts table and save
                db.Posts.Add(post);
                db.SaveChanges();

                // once post has been created, return to home page
                return RedirectToAction("Index", "Home");
            }

            else
            {
                // if model is invalid, throw error
                ModelState.AddModelError("", "Post creation failed.");
            }

            return View(post);
        }
        public void TestWithInvalidPostWithoutTitle_ShouldReturnBadRequest()
        {
            var testPost = new Post()
            {
                Tags = new List<Tag>() { new Tag()
                        {
                            Name = "technology"
                        },
                       
                },
                Text = "this is just a test post"
            };

            var testUser = new UserModel()
            {
                Username = "******",
                DisplayName = "VALIDNICK",
                AuthCode = new string('b', 40)
            };
            LoggedUserModel userModel = RegisterTestUser(httpServer, testUser);

            var headers = new Dictionary<string, string>();
            headers["X-sessionKey"] = userModel.SessionKey;

            var response = httpServer.Post("api/posts", testPost, headers);
            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
        }
        public void TestGetPostsByValidTags_ShoudReturnValidPosts()
        {
            var testUser = new UserModel()
            {
                Username = "******",
                DisplayName = "VALIDNICK",
                AuthCode = new string('b', 40)
            };
            LoggedUserModel userModel = RegisterTestUser(httpServer, testUser);
            var headers = new Dictionary<string, string>();
            headers["X-sessionKey"] = userModel.SessionKey;

            var testPost = new Post()
            {
                Title = "Test post",
                Tags = new List<Tag>() { new Tag()
                        {
                            Name = "technology"
                        },
                       new Tag()
                        {
                            Name = "it"
                        },
                },
                Text = "this is just a test post"
            };

            httpServer.Post("api/posts", testPost, headers);

            var response = httpServer.Get("api/posts?tags=technology,it", headers);

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.IsNotNull(response.Content);
        }
Exemplo n.º 4
0
        public static CreatePostResponseModel PostToCreatePostResponseModel(Post post)
        {
            var postResponseModel = new CreatePostResponseModel()
            {
                Title = post.Title,
                PostId = post.PostId
            };

            return postResponseModel;
        }
Exemplo n.º 5
0
        public static Post CreatePostModelToPost(CreatePostModel postModel)
        {
            var post = new Post()
                {
                    Title = postModel.Title,
                    Text = postModel.Text,
                    PostDate = DateTime.Now
                };

            return post;
        }
Exemplo n.º 6
0
 public Post GetById([FromUri]int id)
 {
     var postsQuery = this.Data.Posts.GetById(id);
     var post = new Post()
     {
         Title = postsQuery.Title,
         UserId = postsQuery.User.Id,
         Content = postsQuery.Content
     };
     return post;
 }
        // Add: api/Posts
        public IHttpActionResult PostPost(Post post)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            repository.Add(post);
            repository.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = post.Id }, post);
        }
Exemplo n.º 8
0
        public async Task<IHttpActionResult> CreateNewPost(PostBindingModels.PostBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var post = new Post()
            {
                Title = model.Title,
                UserId = this.User.Identity.GetUserId(),
                Content = model.Content
            };

            this.Data.Posts.Add(post);
            this.Data.SaveChanges();

            return Ok(post);
        }
Exemplo n.º 9
0
        protected void InsertPostBtn_Click(object sender, EventArgs e)
        {

            if (IsValid)
            {
                var postContent = this.PostContent.Text;
                int id = int.Parse(Request.Params["id"]);

                var context = new BlogSystemEntities();

                var author = context.AspNetUsers.FirstOrDefault(user => user.UserName == User.Identity.Name);

                Post post = new Post()
                {
                    PostContent = postContent,
                    AspNetUser = author,
                    TopicId = id
                };

                //if (this.PostImgUpload.HasFile)
                //{
                //    string extension = Path.GetExtension(PostImgUpload.FileName.ToString());
                //    if (extension.Trim().ToLower() == ".png")
                //    {
                //        this.PostImgUpload.SaveAs(Server.MapPath("~/Images/" + PostImgUpload.FileName.ToString()));

                //        Server.MapPath("~/Images/" + PostImgUpload.FileName.ToString());

                //        post.Image = PostImgUpload.FileName.ToString();
                //    }
                //}

                context.Posts.Add(post);
                context.SaveChanges();

                this.PostContent.Text = "";
                this.CurrentTopicListView.DataBind();

            }
        }
        public void TestLeaveValidComment_ShouldReturnCreated()
        {
            //Create test user
            var testUser = new UserModel()
            {
                Username = "******",
                DisplayName = "VALIDNICK",
                AuthCode = new string('b', 40)
            };
            LoggedUserModel userModel = RegisterTestUser(httpServer, testUser);
            var headers = new Dictionary<string, string>();
            headers["X-sessionKey"] = userModel.SessionKey;

            //Create test post
            var testPost = new Post()
            {
                Title = "Test post",
                Tags = new List<Tag>() { new Tag()
                        {
                            Name = "technology"
                        },
                       
                },
                Text = "this is just a test post"
            };
            var createPostResponse = httpServer.Post("api/posts", testPost, headers);
            string createPostResponseBody = createPostResponse.Content.ReadAsStringAsync().Result;
            var postResponse = JsonConvert.DeserializeObject<CreatePostResponseModel>(createPostResponseBody);

            var comment = new Comment()
                {
                    PostDate = DateTime.Now,
                    Text = "Abe kefi me toq post"
                };

            var commentCreateResponse = httpServer.Put("api/posts/" + postResponse.PostId + "/comment", comment,
                                                        headers);
            Assert.AreEqual(HttpStatusCode.Created, commentCreateResponse.StatusCode);
        }
Exemplo n.º 11
0
        public static PostModel PostToPostModel(Post post)
        {
            var postModel = new PostModel()
                {
                    Text = post.Text,
                    Title = post.Title,
                    PostId = post.PostId,
                    PostDate = post.PostDate,
                    PostedBy = post.PostedBy == null ? null : post.PostedBy.DisplayName,
                };

            foreach (var comment in post.Comments)
            {
                postModel.Comments.Add(CommentToPostCommentModel(comment));
            }

            foreach (var tag in post.Tags)
            {
                postModel.Tags.Add(tag.Name);
            }

            return postModel;
        }
Exemplo n.º 12
0
        public HttpResponseMessage PostNewPost(PostNewModel model,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
              () =>
              {
                  var context = new BlogSystemContext();
                  using (context)
                  {
                      var user = context.Users.FirstOrDefault(
                          usr => usr.SessionKey == sessionKey);
                      if (user == null)
                      {
                          throw new InvalidOperationException("Invalid sessionKey");
                      }

                      if (model.Title == null || model.Text == null)
                      {
                          throw new ArgumentNullException("Post title or post text cannot be null");
                      }

                      string[] titleWords = model.Title.Split(
                          new char[] { ' ', ',', '.', '!', '?', '\'', '(', ')' },
                          StringSplitOptions.RemoveEmptyEntries);

                      IList<Tag> tags = new List<Tag>();
                      if (model.Tags != null)
                      {
                          foreach (var item in model.Tags)
                          {
                              var tag = context.Tags.FirstOrDefault(t => t.Name == item.ToLower());
                              if (tag == null)
                              {
                                  tag = new Tag()
                                  {
                                      Name = item.ToLower()
                                  };

                                  context.Tags.Add(tag);
                                  context.SaveChanges();
                              }

                              tags.Add(tag);
                          }
                      }

                      foreach (var item in titleWords)
                      {
                          var tag = context.Tags.FirstOrDefault(t => t.Name == item.ToLower());
                          if (tag == null)
                          {
                              tag = new Tag()
                              {
                                  Name = item.ToLower()
                              };

                              context.Tags.Add(tag);
                              context.SaveChanges();
                          }

                          tags.Add(tag);
                      }

                      var post = new Post()
                      {
                          Title = model.Title,
                          Text = model.Text,
                          PostDate = DateTime.Now,
                          User = user,
                          Tags = tags
                      };

                      context.Posts.Add(post);
                      context.SaveChanges();

                      var createdModel = new PostCreatedModel()
                      {
                          Id = post.Id,
                          Title = post.Title
                      };

                      var response =
                          this.Request.CreateResponse(HttpStatusCode.Created,
                                          createdModel);
                      return response;
                  }
              });

            return responseMsg;
        }
Exemplo n.º 13
0
        public HttpResponseMessage PostPost(CreatePostModel model,
             [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = ExceptionHandler(
            () =>
            {
                User user;
                var context = new BlogSystemContext();
                using (context)
                {
                    user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);
                    if (user == null)
                    {
                        throw new InvalidOperationException("Invalid username or password");
                    }
                }

                Dictionary<string, Tag> tags = new Dictionary<string, Tag>();

                foreach (var tag in model.Tags)
                {
                    var tagToLower = tag.ToLower();
                    if (!tags.ContainsKey(tagToLower))
                    {
                        Tag newTag = new Tag { Name = tagToLower };
                        tags.Add(tagToLower, newTag);
                    }
                }

                var titleTags = model.Title.Split(' ');

                foreach (var tag in titleTags)
                {
                    var tagToLower = tag.ToLower();
                    if (!tags.ContainsKey(tagToLower))
                    {
                        Tag newTag = new Tag { Name = tagToLower };
                        tags.Add(tagToLower, newTag);
                    }
                }

                List<Tag> filtTags = new List<Tag>();

                foreach (var tag in tags.Values)
                {
                    filtTags.Add(tag);
                }

                var newPost = new Post
                {
                    Title = model.Title,
                    Text = model.Text,
                    Tags = filtTags,
                    PostDate = DateTime.Now,
                    User = user,
                };

                var dbPost = this.postRepository.Add(newPost);

                var postMode = new CreatedPostModel
                {
                    Id = dbPost.Id,
                    Title = dbPost.Title
                };

                var response = this.Request.CreateResponse(HttpStatusCode.Created, postMode);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = postMode.Id }));

                return response;
            });

            return responseMsg;
        }
Exemplo n.º 14
0
        public HttpResponseMessage PostCreatePost(
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey ,
            [FromBody]CreatePostModel postToAdd)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
                () =>
                {
                    var context = new BlogDb();
                    using (context)
                    {
                        UserPersister.ValidateSessionKey(sessionKey);

                        var user = context.Users.FirstOrDefault(
                            usr => usr.SessionKey == sessionKey);

                        if (user == null)
                        {
                            throw new InvalidOperationException("Invalid username or password");
                        }
                        List<Tag> tags = new List<Tag>();
                       
                        var wordsFromTitle = postToAdd.Title.Split(new char[] { ' ', ',' },
                            StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; i < wordsFromTitle.Length; i++)
                        {
                            tags.Add(new Tag() { TagName = wordsFromTitle[i].ToLower() });
                        }
                      
                        for (int i = 0; i < postToAdd.Tags.Length; i++)
                        {
                            tags.Add(new Tag() { TagName = postToAdd.Tags[i].ToLower() });
                        }

                        var post = new Post()
                        {
                            Title = postToAdd.Title,
                            DateCreated = DateTime.Now,
                            UserOfPost = user,
                            Text = postToAdd.Text,
                            Tags = tags
                        };
                       
                        context.Posts.Add(post);
                        context.SaveChanges();

                        CreatedPostModel postModel = new CreatedPostModel() { Id = post.PostId, Title = post.Title };
                      

                        var response =
                            this.Request.CreateResponse(HttpStatusCode.Created,
                                postModel);
                        return response;
                    }
                });

            return responseMsg;
        }
Exemplo n.º 15
0
        public HttpResponseMessage Post([FromUri]string sessionKey, [FromBody]PostDto postDto)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
                () =>
                {
                    var db = new BlogContext();

                    if (sessionKey.Length != SessionKeyLength)
                    {
                        throw new ArgumentException("Invalid session key.");
                    }

                    var user = db.Users.Where(u => u.SessionKey == sessionKey).FirstOrDefault();

                    if (user == null)
                    {
                        throw new ApplicationException("Invalin session. Try to login.");
                    }

                    if (postDto == null)
                    {
                        throw new ArgumentException("Cannot create empty post.");
                    }

                    if (postDto.Title == null)
                    {
                        throw new ArgumentException("Cannot create post without title");
                    }

                    if (postDto.Content == null)
                    {
                        throw new ArgumentException("Cannot create post without text");
                    }

                    var post = new Post() 
                    { 
                        Title = postDto.Title, 
                        Content = postDto.Content, 
                        PostDate = DateTime.Now
                    };

                    if (postDto.Tags != null)
                    {
                        foreach (var tag in postDto.Tags)
                        {
                            post.Tags.Add(new Tag() { TagText = tag });
                        }
                    }

                    var tagsFromTitle = 
                        postDto.Title.Split(new char[]{ ' ', ',', '.', '?', '!' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var tag in tagsFromTitle)
                    {
                        post.Tags.Add(new Tag() { TagText = tag });
                    }

                    db.Posts.Add(post);
                    db.SaveChanges();

                    var responsPost = new PostCreateResponseDto() { Id = post.Id, Title = post.Title };

                    var response = this.Request.CreateResponse(HttpStatusCode.Created, responsPost);

                    return response;
                });

            return responseMsg;
        }
Exemplo n.º 16
0
        public void AddPost()
        {
            Random rnd = new Random();

            if (this.view.AuthorId == null)
            {
                throw new ArgumentException("User have to be logged in to add new post");
            }

            if (this.view.PostTitle.IsNullOrWhiteSpace())
            {
                throw new ArgumentException("Title cannot be null or whitespace");
            }

            if (this.view.Content.IsNullOrWhiteSpace())
            {
                throw new ArgumentException("Content cannot be null or whitespace");
            }

            var category = this.Data.Categories.All().FirstOrDefault(c => c.Name == this.view.Category);

            if (category == null)
            {
                throw new ArgumentException("Not existing Category");
            }

            List<string> tagsNames = this.view.Tags.Split(',').Select(p => p.Trim()).ToList();

            List<Tag> tags = new List<Tag>();

            if (tagsNames.Any(t => t != string.Empty))
            {
                tags = this.Data.Tags.All().Where(t => tagsNames.Contains(t.Name)).ToList();

                foreach (var tagName in tagsNames)
                {
                    if (!tags.Any(t => t.Name == tagName))
                    {
                        var tag = new Tag { Name = tagName, Slug = this.CreateSlug(tagName) };
                        this.Data.Tags.Add(tag);
                    }
                }

                this.Data.SaveChanges();
                tags = this.Data.Tags.All().Where(t => tagsNames.Contains(t.Name)).ToList();
            }

            var post = new Post
                           {
                               Title = this.view.PostTitle,
                               Slug =
                                   this.CreateSlug(
                                       string.Format("{0}-{1}", this.view.PostTitle, rnd.Next(10000,100000))),
                               Content = this.view.Content,
                               CategoryId = category.Id,
                               AuthorId = this.view.AuthorId,
                               DateCreated = DateTime.Now,
                               Tags = tags
                           };

            this.Data.Posts.Add(post);
            this.Data.SaveChanges();
        }
        public HttpResponseMessage PostCreatePost(PostModel model,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                this.ValidateSessionKey(sessionKey);

                if (model == null)
                {
                    throw new InvalidOperationException("Model cannot be null");
                }

                var context = new BlogSystemContext();
                using (context)
                {
                    User user = context.Users.Where(usr => usr.SessionKey == sessionKey).FirstOrDefault();
                    if (user == null)
                    {
                        throw new InvalidOperationException("Invalid sessionkey");
                    }

                    var titleTags = model.Title.Split(
                        new char[] { '.', ',', ';', '!', '?', ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    var newTags = new HashSet<Tag>();
                    foreach (var tagName in titleTags)
                    {
                        Tag newtag = new Tag()
                        {
                            Name = tagName.ToLower()
                        };

                        if (!newTags.Contains(newtag))
                        {
                            newTags.Add(newtag);
                        }
                    }

                    foreach (var tagName in model.Tags)
                    {
                        Tag newtag = new Tag()
                        {
                            Name = tagName.ToLower()
                        };

                        if (!newTags.Contains(newtag))
                        {
                            newTags.Add(newtag);
                        }
                    }

                    var newDbTags = new HashSet<Tag>();
                    foreach (var tag in newTags)
                    {
                        var tagDb = context.Tags.FirstOrDefault(tg => tg.Name == tag.Name);
                        if (tagDb == null)
                        {
                            newDbTags.Add(tag);
                        }
                        else
                        {
                            newDbTags.Add(tagDb);
                        }
                    }

                    var post = new Post()
                    {
                        Title = model.Title,
                        Text = model.Text,
                        DatePosted = DateTime.Now,
                        User = user,
                        Tags = newDbTags
                    };

                    user.Posts.Add(post);
                    context.SaveChanges();

                    var responseModel = new CreatePostResponseModel()
                    {
                        Title = post.Title,
                        Id = post.Id
                    };

                    var response = this.Request.CreateResponse(HttpStatusCode.Created, responseModel);

                    return response;
                }
            });

            return responseMsg;
        }
        public IHttpActionResult PutPost(int id, Post post)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != post.Id)
            {
                return BadRequest();
            }

            repository.Update(post);
            repository.SaveChanges();

            return this.Ok(post);
        }
        public ActionResult Edit(Post post)
        {
            // verify that provided model is valid
            if (ModelState.IsValid)
            {
                // update and save edited values
                db.Entry(post).State = EntityState.Modified;
                db.SaveChanges();

                // once edits have been completed, return to home page
                return RedirectToAction("Index", "Home");
            }

            else
            {
                // if model is invalid, throw error
                ModelState.AddModelError("", "Post editing failed.");
            }

            return View(post);
        }