/* * { "title": "NEW POST", * "tags": ["post"], * "text": "this is just a test post" } */ public HttpResponseMessage PostAdd(PostModel model, [ValueProvider(typeof(HeaderValueProviderFactory <string>))] string sessionKey) { var responseMsg = this.PerformOperationAndHandleExceptions( () => { var context = new BloggingSystemContext(); using (context) { if (sessionKey == null) { throw new ArgumentNullException("You dont have session"); } var user = context.Users.FirstOrDefault( usr => usr.SessionKey == sessionKey); if (user == null) { throw new InvalidOperationException("Your session is expired"); } if (model.Title == null) { throw new ArgumentNullException("You dont have title"); } if (model.Text == null) { throw new ArgumentNullException("You dont have text"); } var post = new Post() { Title = model.Title, Text = model.Text, Author = user, PostDate = DateTime.Now }; string[] tagsTile = model.Title.Split(new char[] { ' ' }); for (int i = 0; i < tagsTile.Length; i++) { var tagEnt = new Tag() { Name = tagsTile[i].ToLower() }; var tag = context.Tags.FirstOrDefault(t => t.Name == tagEnt.Name); if (tag == null) { post.Tags.Add(tagEnt); } else { post.Tags.Add(tag); } } if (model.Tags != null) { foreach (var tag in model.Tags) { var tagEnt = new Tag() { Name = tag.ToLower() }; var tagTitle = context.Tags.FirstOrDefault(t => t.Name == tagEnt.Name); if (tagTitle == null) { post.Tags.Add(tagEnt); } else { post.Tags.Add(tagTitle); } } } context.Posts.Add(post); context.SaveChanges(); var createdPost = new CreatedPostModel() { Id = post.Id, Title = post.Title }; var response = this.Request.CreateResponse(HttpStatusCode.Created, createdPost); return(response); } }); return(responseMsg); }
public HttpResponseMessage PostCreate(PostModel postModel, [ValueProvider(typeof(HeaderValueProviderFactory <string>))] string sessionKey) { var responseMessage = this.PerformOperationAndHandleExceptions( () => { //F**k repository pattern -> it's buggy! I'ma use context here... var context = new BlogEntities(); using (context) { var user = context.Users.FirstOrDefault(x => x.SessionKey == sessionKey); if (user == null) { throw new InvalidOperationException("Invalid username"); } var post = new Post { Title = postModel.Title, Text = postModel.Text, User = user, PostedOn = DateTime.Now, }; context.Posts.Add(post); context.SaveChanges(); foreach (var tag in postModel.Tags) { var existingTag = context.Tags.Where(x => x.Name == tag).FirstOrDefault(); if (existingTag == null) { existingTag = new Tag { Name = tag }; } post.Tags.Add(existingTag); } context.SaveChanges(); var createdPost = new CreatedPostModel { Title = post.Title, Id = post.Id }; var response = this.Request.CreateResponse(HttpStatusCode.Created, createdPost); return(response); } }); return(responseMessage); }