//private void TagCreator(IEnumerable<string> tags) //{ // var toCreate = new List<Tag>(); // foreach (var tag in tags) // { // if (_context.Find(typeof(Tag), tag)) // } //} /// <summary> /// Creates new post /// </summary> public async Task Add(string usrId, string title, string description, bool _allowComment, string content, string usrTags, int categoryId) { var tags = usrTags.Split(','); Category cat = _context.Categories.Find(categoryId); var ussr = await UserManager.FindByNameAsync(usrId); var post = new Models.Post { Title = title, Description = description, Content = content, Author = ussr, AuthorId = 1, CreateTime = DateTime.Now, UpdateTime = DateTime.Now, allowComment = _allowComment, Tags = tags.Select(x => new Tag { Title = x }).ToList(), Comments = new List <PostComment>(), Categories = new List <Category>() }; post.Categories.Add(cat); _context.Posts.Add(post); _context.SaveChanges(); }
public void Post_ShouldCreateNewPostAndReturnSuccess() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var releaseToCreate = new Models.Post { Summary = "toto", Kind = "Release", PublishDateTime = DateTime.Now }; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- var result = Controller().AddPost(releaseToCreate) as ObjectResult; //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- result.Should().BeOfType <CreatedAtRouteResult>("because the create operation should go smoothly"); result.StatusCode.Should().Be(201, "because HTTP Status 201 should be returned upon creation of new post"); var model = result.Value as Models.Post; model.Summary.Should().Be(releaseToCreate.Summary); model.Kind.Should().Be(releaseToCreate.Kind); // this will throw if the System-Under-Test (SUT) i.e. the controller didn't call repository.AddEntity(...) //mockRepository.Verify(); }
public void Put_ShouldUpdateEntityAndReturnSuccess() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var dbPost = TestData.CreateDbPost(); context.NewsRelease.Add(dbPost); context.SaveChanges(); Models.Post expectedModelReturn = dbPost.ToModel(mapper); expectedModelReturn.Kind = "Release"; expectedModelReturn.Summary = "toto"; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- var result = Controller().UpdatePost(dbPost.Key, expectedModelReturn) as ObjectResult; //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- result.Should().BeOfType(typeof(OkObjectResult), "because the update operation should go smoothly"); var model = result.Value as Models.Post; model.Summary.Should().Be(expectedModelReturn.Summary); model.Kind.Should().Be(expectedModelReturn.Kind); }
public ActionResult LikePost(int id) { Models.Post thePost = db.Posts.Find(id); thePost.Likes++; db.SaveChanges(); return(Content(thePost.Likes + " likes")); }
public static List <Models.Post> MakePostList(string imgdirpath) { List <Models.Post> outlist = new List <Models.Post>(); using (var db = new myFaceDAL.Entities()) { LoadImagesToFiles(imgdirpath); var q = db.Posts.Select(x => x).ToList(); foreach (myFaceDAL.Post p in q) { Models.Post px = new Models.Post() { id = p.postId, parentid = p.originalPostId == null ? 0 : p.originalPostId.Value, dislikecount = p.dislikeCount, likecount = p.likeCount, publisherid = p.publisherId, postheader = p.postHeader, textcontent = p.postText }; if (db.Images.Where(x => x.postid == p.postId).First() != null) { px.imagefname = imgdirpath + db.Images.Where(x => p.postId == x.postid).First().filename; } outlist.Add(px); } } return(outlist); }
internal static void UpdateFromModel(this NewsRelease dbPost, Models.Post post, HubDbContext dbContext) { dbContext.Entry(dbPost).CurrentValues.SetValues(post); dbPost.ReleaseType = Enum.Parse <ReleaseType>(post.Kind); var newsReleaseLanguage = dbPost.NewsReleaseLanguage.FirstOrDefault(); if (newsReleaseLanguage == null) { newsReleaseLanguage = new NewsReleaseLanguage() { LanguageId = Language.enCA }; dbPost.NewsReleaseLanguage.Add(newsReleaseLanguage); } newsReleaseLanguage.Location = post.Location; newsReleaseLanguage.Summary = post.Summary; dbPost.Ministry = dbContext.Ministry.FirstOrDefault(m => m.Key == post.LeadMinistryKey); if (post.MinistryKeys != null) { dbContext.NewsReleaseMinistry.RemoveRange(dbPost.NewsReleaseMinistry.Where(m => !post.MinistryKeys.Contains(m.Ministry.Key))); foreach (var newMinistry in post.MinistryKeys.Where(sh => !dbPost.NewsReleaseMinistry.Any(m => m.Ministry.Key == sh))) { dbPost.NewsReleaseMinistry.Add(new NewsReleaseMinistry { Release = dbPost, Ministry = dbContext.Ministry.Single(m => m.Key == newMinistry) }); } } dbPost.Timestamp = DateTimeOffset.Now; }
public IActionResult CreatePost([FromBody] Models.Post post) { this.apiDbContext.Posts.Add(post); this.apiDbContext.SaveChanges(); return(Ok()); }
public Models.Post Update(string slug, Models.Post post) { try { var postEntity = _context.Posts.Where(x => x.Slug == slug).FirstOrDefault(); postEntity.Slug = CreateSlugWithEnglishChar(post); postEntity.Title = post.Title; postEntity.Description = post.Description; postEntity.Body = post.Body; postEntity.Tag = post.Tag; postEntity.CreatedAt = post.CreatedAt; postEntity.UpdatedAt = post.UpdatedAt; _context.Posts.Attach(postEntity); _context.Posts.Update(postEntity); _context.SaveChanges(); return(_mapper.Map <Models.Post>(postEntity)); } catch (Exception e) { throw new Exception(e.Message); } }
public async Task <PostViewModel> Post([FromBody] PostInputModel model) { var post = new Models.Post { Content = model.Description, Title = model.Title, OwnerId = CurrentUserId, OwnerName = User.Identity.Name }; await _postRepo.AddAsync(post); var response = new PostViewModel() { Id = post.Id, Title = post.Title, Description = post.Content, OwnerName = post.OwnerName, CreatedDate = post.Created }; await _postMessageHubContext.Clients.All.InvokeAsync("AddPostSuccess", response); return(response); }
public async Task <IActionResult> OnPost() { if (ModelState.IsValid) { try { Models.Post post = new Models.Post { Title = BindPost.Title, Description = BindPost.Description, Text = BindPost.Text, Author = BindPost.Author, Category_id = BindPost.Category_id, Secret = BindPost.Secret }; await _context.Posts.AddAsync(post); await _context.SaveChangesAsync(); } catch (Exception) { } return(RedirectToPage("../Index")); } return(RedirectToPage("../Index")); }
public void _Returns_Correct_Model( string cloud, string apiKey, string apiSecret, int postId) { //Arrange var post = new Models.Post(); var model = new PostDetailsViewModel(); var mockedAuthProvider = new Mock <IAuthenticationProvider>(); var mockedPostService = new Mock <IPostService>(); mockedPostService.Setup(s => s.GetPostById(It.IsAny <int>())).Returns(post); var mockedViewModelFactory = new Mock <IViewModelFactory>(); mockedViewModelFactory.Setup(v => v.CreatePostDetailsViewModel(It.IsAny <Models.Post>())).Returns(model); var mockedAcc = new CloudinaryDotNet.Account(cloud, apiKey, apiSecret); var mockedCloudinary = new Mock <Cloudinary>(mockedAcc); var postController = new PostController(mockedAuthProvider.Object, mockedPostService.Object, mockedViewModelFactory.Object, mockedCloudinary.Object); //Act var res = postController.Details(postId) as ViewResult; //Assert Assert.AreEqual(model, res.Model); }
private PostAnswerDTO PostAnswerDTOFromModel(Models.Post post) { return(new PostAnswerDTO(post.PostId, post.CreationDate, post.Body, post.Score)); }
public string AddPost(string blogid, string username, string password, WilderMinds.MetaWeblog.Post post, bool publish) { ValidateUser(username, password); var newPost = new Models.Post { Title = post.title, //Done:假如mt_excerpt為null,取文章前N個字 Excerpt= string.IsNullOrWhiteSpace(post.mt_excerpt)? HtmlHelper.HtmlInnerText(post.description): post.mt_excerpt, Content = post.description, IsPublished = publish, Categories = post.categories }; //TODO:做成可選擇GUID/時間格式/Title模式 newPost.Slug = !string.IsNullOrWhiteSpace(post.wp_slug) ? post.wp_slug : newPost.ID;//(Models.Post.CreateSlug(post.title)) if (post.dateCreated != DateTime.MinValue) { newPost.PubDate = post.dateCreated.ToUniversalTime(); } _blog.SavePost(newPost).GetAwaiter().GetResult(); return newPost.ID; }
public void Edit(string id, Models.Post updatedItem) { using (var db = new CmsContext()) { var post = db.Posts.SingleOrDefault(p => p.Id == id); if (post == null) { throw new KeyNotFoundException("A post with the id of " + id + " does not exist in the data store."); } post.Id = updatedItem.Id; post.Title = updatedItem.Title; if (updatedItem.ImageUpload != null) { post.ImageUrl = updatedItem.ImageUrl; } post.Content = updatedItem.Content; post.Published = updatedItem.Published; post.Tags = updatedItem.Tags; post.Price = updatedItem.Price; db.SaveChanges(); } }
GetAsync() { System.Collections.Generic.List <Models.Post> result = null; await System.Threading.Tasks.Task.Run(() => { result = new System.Collections.Generic.List <Models.Post>(); for (int index = 1; index <= 10; index++) { var post = new Models.Post { Id = index, Body = $"Body { index }", Title = $"Title { index }", }; result.Add(post); } }); return(result); }
public List<Post> GetPosts() { List<Post> posts = new List<Post>(); using(IDbConnection dbcon = new MySqlConnection(connectionString)) { dbcon.Open(); using(IDbCommand dbcmd = dbcon.CreateCommand()) { dbcmd.CommandText = "SELECT * FROM Posts ORDER BY Date DESC"; using(IDataReader reader = dbcmd.ExecuteReader()) { while(reader.Read()) { Models.Post post = new Models.Post(); post.Index = Convert.ToInt32(reader["Index"]); post.Name = reader["Name"].ToString(); post.Subject = reader["Subject"].ToString(); post.Comment = reader["Comment"].ToString(); post.ThumbFile = reader["ThumbFile"].ToString(); post.FullFile = reader["FullFile"].ToString(); post.Date = Convert.ToDateTime(reader["Date"]); posts.Add(post); } } } } return posts; }
public async Task <IActionResult> OnPostPostingAsync(string postText, int?teamId, int?eventId) { if (string.IsNullOrEmpty(postText)) { return(Page()); } await LoadContextAsync(teamId, eventId); if (Event == null) { return(Page()); } Models.Post post = new Models.Post() { TeamId = Event.TeamId, PersonId = Me.Id, Date = DateTime.Now, Text = postText }; await postRepo.AddPostAsync(post); await mailService.SendPostMailAsync(post); return(RedirectToPage("./Index", new { teamId, eventId })); }
public void SeedData() { Tag tag1 = Tags.Add(new Tag { Name = "Artist" }).Entity; Tag tag2 = Tags.Add(new Tag { Name = "Likes hiking" }).Entity; Tag tag3 = Tags.Add(new Tag { Name = "Likes cooking" }).Entity; Tag tag4 = Tags.Add(new Tag { Name = "Vegan" }).Entity; User mary = Users.Add(new User { Name = "Mary", Wall = new Models.Wall() }).Entity; User john = Users.Add(new User { Name = "John", Wall = new Models.Wall(), }).Entity; User louise = Users.Add(new User { Name = "Louise", Wall = new Models.Wall() }).Entity; UserTag maryTag1 = new UserTag { User = mary, Tag = tag1 }; UserTag maryTag2 = new UserTag { User = mary, Tag = tag2 }; UserTag louiseTag2 = new UserTag { User = louise, Tag = tag2 }; UserTag louiseTag3 = new UserTag { User = louise, Tag = tag3 }; mary.UserTags.Add(maryTag1); mary.UserTags.Add(maryTag2); louise.UserTags.AddRange(new UserTag[] { louiseTag2, louiseTag3 }); Post post1 = new Models.Post { Content = "hello", User = mary, DatePosted = DateTime.Now, Wall = john.Wall }; Post post2 = new Models.Post { Content = "hi!", User = mary, DatePosted = DateTime.Now, Wall = louise.Wall }; Post post3 = new Models.Post { Content = "hello again!", User = john, DatePosted = DateTime.Now, Wall = mary.Wall }; Post post4 = new Models.Post { Content = "post4", User = john, DatePosted = DateTime.Now, Wall = louise.Wall }; Posts.AddRange(post1, post2, post3, post4); UserTags.AddRange(maryTag1, maryTag2, louiseTag2, louiseTag3); SaveChanges(); }
/// <summary> /// Method to update a post /// </summary> /// <param name="objPost">Element with all data to save</param> /// <param name="strProfile">Profile of user. 1= writer, 2=editor</param> /// <param name="strName">User name</param> public void Update(Models.Post objPost, string strProfile, string strName) { using (var context = new Entity.blog_dbEntities()) { //elemento a actualizar var update = context.posts.FirstOrDefault(t => t.post_id == objPost.IdPost); //Se actualiza if (strProfile == "1") { //writer profile update.post_title = objPost.strTitle.Trim(); update.post_text = objPost.strText.Trim(); update.post_author = objPost.strAuthor.Trim(); update.post_change = DateTime.Now; update.post_status_published = objPost.blnStatusToPublish == true ? 1 : 0; } else { //editor profile update.post_status_published = objPost.blnStatusToPublish == true ? 2 : 0; if (objPost.blnStatusToPublish == true) { update.post_approval = DateTime.Now; update.post_approval_name = strName; } } context.SaveChanges(); } }
public ActionResult Edit(int id) { //get the post to edit from the db Models.Post postToEdit = db.Posts.Find(id); //pass our post to edit to the view return(View(postToEdit)); }
protected void btnSua_Click(object sender, EventArgs e) { try { Models.NewsEntities db = new Models.NewsEntities(); int Id = Convert.ToInt32(txtMaBV.Text); string tenbv = txtTenBV.Text; string mota = txtMoTa.Text; string noidung = txtNoiDung.Text; string tacgia = txtTacGia.Text; Models.Post obj = db.Post.FirstOrDefault(x => x.Id == Id); if (Id != null && tenbv != null && tenbv != "" && mota != null && mota != "" && noidung != null && noidung != "" && tacgia != null && tacgia != "") { obj = new Models.Post(); obj.TenBV = txtTenBV.Text; obj.MoTa = txtMoTa.Text; obj.NoiDung = txtNoiDung.Text; obj.TacGia = txtTacGia.Text; db.Post.Add(obj); db.SaveChanges(); Response.Redirect("QuanLyBaiViet.aspx"); } else { pnError.Visible = true; lbError.Text = "Các trường không được để trống!"; } } catch { pnError.Visible = true; lbError.Text = "Lỗi, không lưu lại được !"; } }
public ActionResult Delete(int id) { //get the post from the database Models.Post postToDelete = db.Posts.Find(id); //pass the object to the view return(View(postToDelete)); }
private void SeedDb() { this.TruncatePostReportsTable(); this.TruncatePostsTable(); this.TruncateUsersTable(); var author = new ForumUser { Id = TestsConstants.TestId }; this.dbService.DbContext.Users.Add(author); this.dbService.DbContext.SaveChanges(); var post = new Models.Post { Id = TestsConstants.TestId1, Author = author, AuthorId = author.Id }; this.dbService.DbContext.Posts.Add(post); this.dbService.DbContext.SaveChanges(); var firstPostReport = new PostReport { Id = TestsConstants.TestId, Author = author, AuthorId = author.Id }; this.dbService.DbContext.PostReports.Add(firstPostReport); this.dbService.DbContext.SaveChanges(); for (int i = 0; i < 5; i++) { var postReport = new PostReport(); this.dbService.DbContext.PostReports.Add(postReport); this.dbService.DbContext.SaveChanges(); } }
public async Task <string> AddPostAsync(string blogId, string username, string password, Post post, bool publish) { ValidateUser(username); if (post is null) { throw new ArgumentNullException(nameof(post)); } var newPost = new Models.Post { Title = post.title, Slug = !string.IsNullOrWhiteSpace(post.wp_slug) ? post.wp_slug : Models.Post.CreateSlug(post.title), Excerpt = post.mt_excerpt, Content = post.description, IsPublished = publish }; post.categories.ToList().ForEach(newPost.Categories.Add); if (post.dateCreated != DateTime.MinValue) { newPost.PubDate = post.dateCreated; } await _blog.SavePost(newPost).ConfigureAwait(false); return(newPost.Id); }
public Task <string> AddPostAsync(string blogid, string username, string password, Post post, bool publish) { ValidateUser(username, password); return(Task.Run(() => { var newPost = new Models.Post { Title = post.title, Slug = !string.IsNullOrWhiteSpace(post.wp_slug) ? post.wp_slug : Models.Post.CreateSlug(post.title), Content = post.description, IsPublished = publish, Categories = post.categories }; if (post.dateCreated != DateTime.MinValue) { newPost.PubDate = post.dateCreated; } _blog.SavePost(newPost).GetAwaiter().GetResult(); return newPost.ID; })); }
public _Forum__PostModel(ForumPostInfo fpi, int curUserID) { CurrentUserID = curUserID; FPI = fpi; newPost = new Models.Post(); newPost.Description = FPI.forumPost.Text; }
public Post(Models.Post model, Models.BaseContext context) { Id = model.Id; Title = model.Title; Text = model.Text; CreatedAt = model.CreatedAt; LastModified = model.LastModified; if (context != null) { var author = context .Users .Find(model.AuthorId); Author = new Views.User(author); var comments = context .Comments .ToList() .Where(x => x.PostId == model.Id); Comments = new List <Comment>(); foreach (Models.Comment comment in comments) { Comments.Add(new Views.Comment(comment, context)); } } }
protected void btnThemMoi_Click(object sender, EventArgs e) { try { // Kiểm tra mã có tồn tại chưa? Models.NewsEntities db = new Models.NewsEntities(); string tenbv = txtTenBV.Text; string mota = txtMoTa.Text; string noidung = txtNoiDung.Text; string tacgia = txtTacGia.Text; if (tenbv != "" && mota != null && mota != "" && noidung != null && noidung != "" && tacgia != null && tacgia != "") { Models.Post obj = new Models.Post(); obj.TenBV = txtTenBV.Text; obj.MoTa = txtMoTa.Text; obj.NoiDung = txtNoiDung.Text; obj.TacGia = txtTacGia.Text; obj.NgayDang = DateTime.Now; obj.Id = Convert.ToInt32(ddlDanhMuc.SelectedValue); db.Post.Add(obj); db.SaveChanges(); Response.Redirect("QuanLyBaiViet.aspx"); } else { pnError.Visible = true; lbError.Text = "Các trường không được để trống!"; } } catch { pnError.Visible = true; lbError.Text = "Lỗi, không lưu lại được !"; } }
public ActionResult Update(PostViewModel postViewModel) { if (postViewModel.Id != 0) { var existingPost = this.BlogSystemDbContext.Posts.FirstOrDefault(p => p.Id == postViewModel.Id); existingPost.Name = postViewModel.Name; existingPost.Content = postViewModel.Content; existingPost.DateCreated = DateTime.Now; existingPost.User = UserManager.FindById(User.Identity.GetUserId()); } else { var newPost = new Models.Post() { Name = postViewModel.Name, Content = postViewModel.Content, DateCreated = DateTime.Now, User = UserManager.FindById(User.Identity.GetUserId()) }; this.BlogSystemDbContext.Posts.Add(newPost); } BlogSystemDbContext.SaveChanges(); return(RedirectToAction("Index", "Home")); }
public string AddPost(string blogid, string username, string password, WilderMinds.MetaWeblog.Post post, bool publish) { ValidateUser(username, password); var newPost = new Models.Post { Title = post.title, Slug = !string.IsNullOrWhiteSpace(post.wp_slug) ? post.wp_slug : Models.Post.CreateSlug(post.title), Content = post.description, IsPublished = publish, PostCategories = post.categories.Select(c => new PostCategory { Category = new Category { Name = c.ToLower() } }).ToList() }; if (post.dateCreated != DateTime.MinValue) { newPost.PubDate = post.dateCreated; } _blog.SavePost(newPost).GetAwaiter().GetResult(); return(newPost.Id); }
public async Task <IActionResult> CreatePost([FromBody] Models.Post post) { context.Posts.Add(post); await context.SaveChangesAsync(); return(Ok(post)); }
/// <summary> /// Creates and publishes a new post /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> public static void FileCreated(object sender, FileSystemEventArgs e) { using (var reader = new StreamReader(e.FullPath)) { var data = GetPost(reader.ReadToEnd()); var name = GetTitle(e.Name); using (var api = App.Instance.IoCContainer.Resolve<IApi>()) { // Create pos var post = new Models.Post() { Title = name, Keywords = data.Keywords, Description = data.Description, Body = data.Content }; AddCategories(api, post, data.Categories); AddTags(api, post, data.Tags); api.Posts.Add(post); api.SaveChanges(); api.Posts.Publish(post.Id.Value, data.Publish); api.SaveChanges(); } } }
public void AddPost(Post newPost) { using (var context = new Models.PostContext()) { Models.Post post = new Models.Post(); post.Title = newPost.Title; post.IsApproved = newPost.IsApproved; post.DatePosted = newPost.DatePosted; post.Content = newPost.Content; post.CatID = newPost.CatID; post.Categories = newPost.Categories.Select(x => new Models.Category() { category = x.category }).ToList(); context.Posts.Add(post); context.SaveChanges(); } }
/// <summary> /// Test the rating repository. /// </summary> protected void Run() { var userId = Guid.NewGuid().ToString(); Models.PostType type = null; Models.Author author = null; Models.Post post = null; using (var api = new Api()) { // Add new post type type = new Models.PostType() { Name = "Rating post", Route = "post" }; api.PostTypes.Add(type); api.SaveChanges(); // Add new author author = new Models.Author() { Name = "Jim Doe", Email = "*****@*****.**" }; api.Authors.Add(author); api.SaveChanges(); // Add new post post = new Models.Post() { TypeId = type.Id, AuthorId = author.Id, Title = "My rated post", Excerpt = "Read my first post.", Body = "<p>Lorem ipsum</p>", Published = DateTime.Now }; api.Posts.Add(post); api.SaveChanges(); } using (var api = new Api()) { // Add ratings api.Ratings.AddRating(Models.RatingType.Star, post.Id, userId); api.Ratings.AddRating(Models.RatingType.Like, post.Id, userId); api.SaveChanges(); } using (var api = new Api()) { // Verify save var model = Client.Models.PostModel.GetById(post.Id).WithRatings(); Assert.AreEqual(1, model.Ratings.Stars.Count); Assert.AreEqual(1, model.Ratings.Likes.Count); // Remove ratings api.Ratings.RemoveRating(Models.RatingType.Star, post.Id, userId); api.Ratings.RemoveRating(Models.RatingType.Like, post.Id, userId); api.SaveChanges(); } using (var api = new Api()) { // Verify remove var model = Client.Models.PostModel.GetById(post.Id).WithRatings(); Assert.AreEqual(0, model.Ratings.Stars.Count); Assert.AreEqual(0, model.Ratings.Likes.Count); // Remove api.Posts.Remove(post.Id); api.PostTypes.Remove(type.Id); api.Authors.Remove(author.Id); api.SaveChanges(); } using (var api = new Api()) { // Verify remove post = api.Posts.GetSingle(where: p => p.Slug == "my-rated-post"); type = api.PostTypes.GetSingle(type.Id); author = api.Authors.GetSingle(author.Id); Assert.IsNull(post); Assert.IsNull(type); Assert.IsNull(author); } }
public async Task PostRepository() { var id = Guid.Empty; // Insert post using (var api = new Api()) { var post = new Models.Post() { Title = "My post", Body = "<p>This is the body</p>" }; post.Categories.Add(new Models.Category() { Name = "My category" }); post.Tags.Add(new Models.Tag() { Name = "My tag" }); api.Posts.Add(post); Assert.IsTrue(post.Id.HasValue); Assert.IsTrue(api.SaveChanges() > 0); id = post.Id.Value; } // Get by slug using (var api = new Api()) { var post = await api.Posts.GetBySlugAsync("my-post"); Assert.IsNotNull(post); Assert.AreEqual(post.Title, "My post"); Assert.AreEqual(post.Categories.Count, 1); Assert.AreEqual(post.Tags.Count, 1); } // Update post using (var api = new Api()) { var post = await api.Posts.GetBySlugAsync("my-post"); Assert.IsNotNull(post); post.Title = "My updated post"; post.Tags.Add(new Models.Tag() { Name = "My second tag" }); api.Posts.Add(post); Assert.IsTrue(api.SaveChanges() > 0); } // Get by id using (var api = new Api()) { var post = await api.Posts.GetByIdAsync(id); Assert.IsNotNull(post); Assert.AreEqual(post.Title, "My updated post"); Assert.AreEqual(post.Categories.Count, 1); Assert.AreEqual(post.Tags.Count, 2); } // Remove post using (var api = new Api()) { var post = await api.Posts.GetBySlugAsync("my-post"); // Remove categories & tags foreach (var c in post.Categories) api.Categories.Remove(c); foreach (var t in post.Tags) api.Tags.Remove(t); api.Posts.Remove(post); Assert.IsTrue(api.SaveChanges() > 0); } }
/// <summary> /// Called when a file in the upload folder is changed. /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> public static void FileChanged(object sender, FileSystemEventArgs e) { using (var reader = new StreamReader(e.FullPath)) { var data = GetPost(reader.ReadToEnd()); var name = GetTitle(e.Name); var isnew = false; using (var api = App.Instance.IoCContainer.Resolve<IApi>()) { var post = api.Posts.GetBySlug(Utils.GenerateSlug(name)); if (post == null) { post = new Models.Post() { Title = name }; isnew = true; } post.Keywords = data.Keywords; post.Description = data.Description; post.Body = data.Content; AddCategories(api, post, data.Categories); AddTags(api, post, data.Tags); api.Posts.Add(post); api.SaveChanges(); if (isnew) { api.Posts.Publish(post.Id.Value, data.Publish); api.SaveChanges(); } } } }
public ActionResult Post(int? id, string message) { if (id == null) { return RedirectToAction("Index", "Chats"); } Post post = new Models.Post(); ; string currentUserId = User.Identity.GetUserId(); var currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId); var currentchat = db.chat.FirstOrDefault(y => y.ID == id); post.message = message; post.time = DateTime.Now; db.post.Add(post); currentUser.posts.Add(post); currentchat.posts.Add(post); db.SaveChanges(); return RedirectToAction("Details/" + id, "Chats"); }
public ActionResult Post(string id) { Models.Post post = new Models.Post(); post.Get(id); return View(post); }
/// <summary> /// Test the post repository. /// </summary> protected void Run() { Models.PostType type = null; Models.Author author = null; Models.Post post = null; using (var api = new Api()) { // Add new post type type = new Models.PostType() { Name = "Test post", Route = "post" }; api.PostTypes.Add(type); api.SaveChanges(); // Add new author author = new Models.Author() { Name = "Jane Doe", Email = "*****@*****.**" }; api.Authors.Add(author); api.SaveChanges(); // Add new post post = new Models.Post() { TypeId = type.Id, AuthorId = author.Id, Title = "My test post", Excerpt = "Read my first post.", Body = "<p>Lorem ipsum</p>", Published = DateTime.Now }; api.Posts.Add(post); api.SaveChanges(); } using (var api = new Api()) { // Get model var model = api.Posts.GetSingle(where: p => p.Slug == "my-test-post"); Assert.IsNotNull(model); Assert.AreEqual("Read my first post.", model.Excerpt); Assert.AreEqual("<p>Lorem ipsum</p>", model.Body); // Update model model.Excerpt = "Updated post"; api.SaveChanges(); } using (var api = new Api()) { // Verify update var model = api.Posts.GetSingle(where: p => p.Slug == "my-test-post"); Assert.IsNotNull(model); Assert.AreEqual("Updated post", model.Excerpt); Assert.AreEqual("<p>Lorem ipsum</p>", model.Body); // Remove api.Posts.Remove(model); api.PostTypes.Remove(type.Id); api.Authors.Remove(author.Id); api.SaveChanges(); } using (var api = new Api()) { // Verify remove post = api.Posts.GetSingle(where: p => p.Slug == "my-test-post"); type = api.PostTypes.GetSingle(type.Id); author = api.Authors.GetSingle(author.Id); Assert.IsNull(post); Assert.IsNull(type); Assert.IsNull(author); } }