public static Post CreateNewEntity(PostModel postModel, User author, BloggingSystemContext context)
        {
            Post postEntity = new Post()
            {
                Title = postModel.Title,
                Author = author,
                PostDate = DateTime.Now,
                Text = postModel.Text
            };

            foreach (var tagName in postModel.Tags)
            {
                postEntity.Tags.Add(Extensions.CreateOrLoadTag(tagName.ToLower(), context));
            }

            var titleTags = postModel.Title.Split(WordSeparators, StringSplitOptions.RemoveEmptyEntries);
            foreach (var titleTagName in titleTags)
            {
                if (titleTagName.Length > 1)
                {
                    postEntity.Tags.Add(Extensions.CreateOrLoadTag(titleTagName.ToLower(), context));
                }
            }

            return postEntity;
        }
        public static PostedPost ToPostedModel(Post postEntity)
        {
            PostedPost postedPost = new PostedPost()
            {
                ID = postEntity.ID,
                Title = postEntity.Title
            };

            return postedPost;
        }
        //POST api/posts/create
        public HttpResponseMessage PostCreate(PostModel post, string sessionKey)
        {
            var context = new BlogContext();
            var responseMsg = this.PerformOperationAndHandleExceptionsWithSessionKey(sessionKey, context, () =>
            {
                HttpResponseMessage response;
                var newPost = new Post();
                using (var tran = new TransactionScope())
                {
                    newPost.Title = post.Title;
                    newPost.Text = post.Text;
                    newPost.PostDate = DateTime.Now;
                    newPost.User = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);

                    var tags = Helpers.GetTags(post, context);
                    tags.ForEach(t => newPost.Tags.Add(t));
                
                    context.Posts.Add(newPost);
                    context.SaveChanges();
                    tran.Complete();
                }

                if (newPost.Id > 0)
                {
                    response = this.Request.CreateResponse(HttpStatusCode.Created, new ResponsePostModel()
                    {
                        Id = newPost.Id,
                        Title = newPost.Title
                    });
                }
                else
                {
                    response = this.Request.CreateResponse(HttpStatusCode.InternalServerError);
                }

                return response;
            });

            return responseMsg;
        }
        public static PostModel ToModel(Post postEntity)
        {
            PostModel postModel = new PostModel()
            {
                ID = postEntity.ID,
                Title = postEntity.Title,
                Text = postEntity.Text,
                PostDate = postEntity.PostDate,
                Author = postEntity.Author.DisplayName
            };

            foreach (var commentEntity in postEntity.Comments)
            {
                postModel.Comments.Add(CommentsMapper.ToModel(commentEntity));
            }

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

            return postModel;
        }
示例#5
0
        public HttpResponseMessage CreatePost(CreatePostDto value)
        {
            try
            {
                var sessionKey = ApiControllerHelper.GetHeaderValue(Request.Headers, "X-SessionKey");
                if (sessionKey == null)
                {
                    throw new ArgumentNullException("No session key provided in the request header!");
                }

                Validate(value.Title, "title");
                Validate(value.Text, "text");

                var context = new BloggingSystemContext();

                using (context)
                {
                    var user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);
                    if (user == null)
                    {
                        throw new ArgumentException("Users must be logged in to create posts!");
                    }

                    var newPost = new Post()
                    {
                        Title = value.Title,
                        Text = value.Text,
                        PostDate = DateTime.Now,
                        Author = user
                    };

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

                    List<string> tagsToCheck = new List<string>();

                    foreach (var tagFromTitle in tagsFromTitle)
                    {
                        tagsToCheck.Add(tagFromTitle);
                    }

                    if (value.Tags != null)
                    {
                        foreach (string tagName in value.Tags)
                        {
                            tagsToCheck.Add(tagName);
                        }
                    }

                    foreach (string tagName in tagsToCheck)
                    {
                        var matchingTag = context.Tags.FirstOrDefault(t => string.Compare(t.Name, tagName, true) == 0);
                        if (matchingTag == null)
                        {
                            // tag not found, insert it in the database
                            matchingTag = new Tag
                            {
                                Name = tagName.ToLower()
                            };

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

                        newPost.Tags.Add(matchingTag);
                    }

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

                    var createdPostDto = new CreatePostDto()
                    {
                        Id = newPost.Id,
                        Title = newPost.Title,
                        Tags = newPost.Tags.Select(t => t.Name),
                        Text = newPost.Text
                    };

                    var response = Request.CreateResponse(HttpStatusCode.Created, createdPostDto);
                    return response;
                }
            }
            catch (Exception ex)
            {
                var errorResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
                throw new HttpResponseException(errorResponse);
            }
        }
示例#6
0
        public HttpResponseMessage PostPosts(Post post, string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
             () =>
             {
                 var context = new BlogContext();
                 using (context)
                 {
                     var user = context.Users.FirstOrDefault(usr =>
                         usr.SessionKey == sessionKey);

                     if (user == null)
                     {
                         throw new InvalidOperationException("Invalid SessionKey!");
                     }

                     var newPost = new Post()
                     {
                         Id = post.Id,
                         Date = post.Date,
                         Title = post.Title,
                         Text = post.Text,
                         Tags = post.Tags,
                         Comments = post.Comments,
                         User = user
                     };

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

                     PostModel response = new PostModel()
                     {
                         Title = newPost.Title,
                         Id = newPost.Id
                     };

                     return this.Request.CreateResponse(HttpStatusCode.OK, response);
                 }
             });

            return responseMsg;
        }
        private void AddTitleTags(BloggingSystemContext context, PostModel postData, Post postEntity)
        {
            var titleTags = postData.Title.ToLower().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (titleTags != null)
            {
                foreach (var tag in titleTags)
                {
                    var tagEntity = this.GetOrCreateTag(context, tag);

                    postEntity.Tags.Add(tagEntity);
                }
            }
        }
        private void AddTags(BloggingSystemContext context, PostModel postData, Post postEntity)
        {
            if (postData.Tags != null)
            {
                foreach (var tag in postData.Tags)
                {
                    var tagEntity = this.GetOrCreateTag(context, tag);

                    postEntity.Tags.Add(tagEntity);
                }
            }
        }
        public HttpResponseMessage PostAddPost(PostModel postData, [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
                () =>
                {
                    var context = new BloggingSystemContext();
                    using (context)
                    {
                        var user = GetAndValidateUser(sessionKey, context);

                        ValidatePost(postData);

                        var postEntity = new Post()
                        {
                            Text = postData.Text,
                            Title = postData.Title
                        };

                        postEntity.PostDate = DateTime.Now;
                        postEntity.User = user;

                        AddTags(context, postData, postEntity);
                        AddTitleTags(context, postData, postEntity);

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

                        var postCreatedModel = new PostCreatedModel() { Id = postEntity.Id, Title = postEntity.Title };

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

            return responseMsg;
        }
        //POST api/posts/
        public HttpResponseMessage PostCreate(PostModel post,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var context = new BloggingSystemContext();
            var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
            var responseMsg = this.PerformOperationAndHandleExceptionsWithSessionKey(
                sessionKey, context, () =>
            {
                var newPost = new Post();
                newPost.Title = post.Title;
                newPost.Text = post.Text;
                newPost.PostDate = DateTime.Now;
                newPost.User = user;
                newPost.Tags = new List<Tag>();

                var pattern = new Regex(
                    @"( [^\W_\d]              # starting with a letter
                                              # followed by a run of either...
                        ( [^\W_\d] |          #   more letters or
                          [-'\d](?=[^\W_\d])  #   ', -, or digit followed by a letter
                        )*
                        [^\W_\d]              # and finishing with a letter
                      )",
                    RegexOptions.IgnorePatternWhitespace);

                foreach (Match m in pattern.Matches(newPost.Title))
                {
                    var tagContent = m.Groups[1].Value.ToLower();
                    if (context.Tags.FirstOrDefault(t => t.Content == tagContent) == null)
                    {
                        newPost.Tags.Add(new Tag()
                        {
                            Content = tagContent,
                        });
                    }
                }

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

                var createdPost = new CreatedPost()
                {
                    Id = newPost.Id,
                    Title = newPost.Title
                };

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

            return responseMsg;
        }
        public HttpResponseMessage PostPost(CreatePostModel model)
        {
            var responseMessage = this.PerformOperationAndHandleExceptions(() =>
            {
                var sessionKey = this.GetHeaderValue(Request.Headers, "sessionKey");
                var dbContext = new BlogContext();
               // dbContext.Configuration.ProxyCreationEnabled = false;

                using (dbContext)
                {
                    var user = dbContext.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
                    if (user == null)
                    {
                        throw new ArgumentException("Users must be logged when create a new post!");
                    }

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

                    if (!(model.Tags==null))
                    {                        
                        foreach (var tagItem in model.Tags)
                        {
                            var tagEntity = new Tag()
                            {
                                Text = tagItem.ToLower()
                            };

                            newTags.Add(tagEntity);
                        }
                    }

                    //split title and add to the tags
                    string[] wordsIntitle = model.Title.Split(new char[] { ' ', ',','.','!','?' });

                    foreach (var word in wordsIntitle)
                    {
                        if (!(word == string.Empty))
                        {
                            var tagEntity = new Tag()
                                {
                                    Text = word.ToLower().Trim()
                                };

                            newTags.Add(tagEntity);
                        }
                    }
                    
                    var newPost = new Post()
                    {
                        Title = model.Title,
                        Text = model.Text,
                        PostDate = DateTime.Now,                        
                        User = user,
                        Tags=newTags
                    };
                    
                    dbContext.Posts.Add(newPost);
                    dbContext.SaveChanges();

                    var postCreatedModel = new CreatedPostModel()
                    {
                        Title = newPost.Title,
                        Id = newPost.Id
                    };
                    var ret = Request.CreateResponse(HttpStatusCode.Created, postCreatedModel);

                   // var ret = Request.CreateResponse(HttpStatusCode.Created);
                    return ret;
                }
            });
            return responseMessage;
        }
        public HttpResponseMessage PostNewPost(PostModel model, string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
                () =>
                {
                    var context = new BlogContext();

                    using (context)
                    {
                        var user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);

                        if (user == null)
                        {
                            throw new InvalidOperationException("Users doesn't exists");
                        }

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

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

                        Post post = new Post();
                        post.Title = model.Title;
                        post.Text = model.Text;
                        post.PostDate = DateTime.Now;
                        post.PostedBy = user;

                        foreach (var tag in model.Tags)
                        {
                            Tag currentTag = CreateOrLoadTag(context, tag.ToLower());
                            post.Tags.Add(currentTag);
                        }

                        string[] titleTags = Regex.Split(model.Title, @"[,!\. ;?']+");

                        foreach (var titleTagName in titleTags)
                        {
                            Tag titleTag = CreateOrLoadTag(context, titleTagName.ToLower());
                            post.Tags.Add(titleTag);
                        }

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

                        var response = this.Request.CreateResponse(HttpStatusCode.Created, new
                        {
                            Title = post.Title,
                            Id = post.Id
                        });

                        return response;
                    }
                });

            return responseMsg;
        }
        public HttpResponseMessage PostCreate(PostModel postModel, 
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.ExceptionHandling(
            () =>
            {
                var context = new BloggingSystemContext();
                using (context)
                {
                    var user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);

                    if (user == null)
                    {
                        throw new InvalidOperationException("Invalid username or password!");
                    }

                    List<string> tags = new List<string>();
                    tags = TakeTags(postModel.Title);
                    foreach (var tagEntity in tags)
                    {
                        var tagInDb = context.Tags.FirstOrDefault(t => t.Name == tagEntity);

                        if(tagInDb == null)
                        {
                            var tag = new Tag()
                            {
                                Name = tagEntity,
                                User = user
                            };
                            context.Tags.Add(tag);
                            context.SaveChanges();
                        }
                    }

                    foreach (var tag in postModel.Tags)
                    {
                        var tagInDb = context.Tags.FirstOrDefault(t => t.Name == tag);

                        if (tagInDb == null)
                        {
                            var newTag = new Tag()
                            {
                                Name = tag,
                                User = user
                            };
                            context.Tags.Add(newTag);
                            context.SaveChanges();
                        }
                    }

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

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

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

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

            return responseMsg;
        }
        public HttpResponseMessage PostAPost(
            [FromBody]PostModel model,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
                {
                    ValidateText(model.Text);
                    ValidateTitle(model.Title);

                    var context = new BloggingSystemContext();
                    using (context)
                    {
                        var user = GetValidUser(sessionKey);

                        if (user == null)
                        {
                            throw new InvalidOperationException("You are not logged in!");
                        }

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

                        HashSet<string> allTags = new HashSet<string>();
                        foreach (var tag in model.Tags)
                        {
                            var lowerTag = tag.ToLower();
                            if (!allTags.Contains(lowerTag))
                            {
                                allTags.Add(lowerTag);
                            }
                        }

                        string[] splitedTitle = model.Title.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var tag in splitedTitle)
                        {
                            var lowerTag = tag.ToLower();
                            if (!allTags.Contains(lowerTag))
                            {
                                allTags.Add(lowerTag);
                            }
                        }

                        foreach (var tag in allTags)
                        {
                            var newTag = context.Tags.Where(t => t.Title == tag).FirstOrDefault();

                            if (newTag == null)
                            {
                                newTag = new Tag()
                                {
                                    Title = tag
                                };
                            }

                            post.Tags.Add(newTag);
                        }

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

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

                        return Request.CreateResponse(HttpStatusCode.Created, responseModel);
                    }
                });

            return responseMsg;
        }