예제 #1
0
        public ActionResult PostingPost(string postContents)
        {
            // Empty postContetns
            if (postContents.IsNullOrWhiteSpace())
            {
                return(RedirectToAction("WallPost"));
            }

            // Create new object of Post - new Post
            var newPost = new Post
            {
                PostContent     = postContents,
                PostDateTime    = DateTime.Now,
                ApplicationUser = _repo.GetUser(User.Identity.Name),
                Tags            = new List <Tag>()
            };

            newPost.ApplicationUser.UserName = User.Identity.Name;

            // Regex- every word after "#"
            var regex = new Regex(@"#\w+");
            // Regex matches in postContents
            var matches = regex.Matches(postContents);

            // Found every tag in database
            var existTag = _repo.GetTag();

            // Every match in postContents
            foreach (Match m in matches)
            {
                if (existTag.Contains(m.Value))
                {
                    var value     = m.Value;
                    var tagInPost = _repo.GetSingleTag(value);
                    // Add tag to post
                    newPost.Tags.Add(tagInPost);
                }
                else
                {
                    // Create new tag in database
                    var newTag = new Tag()
                    {
                        TagName = m.Value
                    };
                    _repo.AddNewTag(newTag);
                    // Add tag to post
                    newPost.Tags.Add(newTag);
                }
            }
            // Add new Post to database
            _repo.AddNewPost(newPost);
            // Save changes in database
            try
            {
                _repo.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var entityValidationErrors in ex.EntityValidationErrors)
                {
                    foreach (var validationError in entityValidationErrors.ValidationErrors)
                    {
                        Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                    }
                }
            }

            // Return to wall with post
            return(RedirectToAction("WallPost"));
        }