public void SavePostItem(PostItem entity) { if (entity.Id == default) { context.Entry(entity).State = EntityState.Added;// объект будет добавлен как новый } else { context.Entry(entity).State = EntityState.Modified;// старый объект будет изменён } context.SaveChanges(); }
public void On_Validate_Valid_PostItem() { // Arrange var postItem = new PostItem { Text = "Teste XPTO", UserId = 1 }; // Act var result = this.validatePostItemService.Validate(postItem); // Assert Assert.IsTrue(result.Count() == 0); }
public void On_Validate_InValid_PostItem() { // Arrange var postItem = new PostItem { }; // Act var result = this.validatePostItemService.Validate(postItem); // Assert Assert.IsTrue(result.Count() == 3); Assert.IsTrue(result.Any(x => x.Message == "Null postItem text")); }
public async Task CallingPostReturnsCreated() { // Arrange var uri = new Uri("http://localhost:36146/v1/Samples"); var content = new PostItem(); // Act var result = await RestCall.CallPostAsync <GetItem, PostItem>(uri, content); // Assert result.Status.Should().Be(HttpStatusCode.Created); }
public async Task <bool> AddPostAsync(PostItem newPost, ApplicationUser user) { newPost.Id = Guid.NewGuid(); newPost.UserId = user.Id; newPost.TimeOfCreation = DateTimeOffset.Now; _context.Posts.Add(newPost); var saveResult = await _context.SaveChangesAsync(); return(saveResult == 1); }
public async Task <IActionResult> PostPostItem([FromBody] PostItem postItem) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _context.PostItem.Add(postItem); await _context.SaveChangesAsync(); return(CreatedAtAction("GetPostItem", new { id = postItem.Id }, postItem)); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { Error = ModelHelper.GetFirstValidationError(ModelState); return(Page()); } var user = await _db.Authors.GetItem(a => a.AppUserName == User.Identity.Name); IsAdmin = user.IsAdmin; PostItem.Author = await _db.Authors.GetItem(a => a.AppUserName == User.Identity.Name); if (ModelState.IsValid) { if (PostItem.Id > 0) { // post can be updated by admin, so use post author id // instead of identity user name var post = _db.BlogPosts.Single(p => p.Id == PostItem.Id); if (post != null) { PostItem.Author = await _db.Authors.GetItem(a => a.Id == post.AuthorId); } } //This is to prevent users from modifiyng other users or admin posts. -- manuta 9-16-2018 if (IsAdmin || _db.Authors.Single(a => a.Id == PostItem.Author.Id).AppUserName == User.Identity.Name) { if (PostItem.Status == SaveStatus.Publishing) { PostItem.Published = DateTime.UtcNow; } if (PostItem.Status == SaveStatus.Unpublishing) { PostItem.Published = DateTime.MinValue; } PostItem.Slug = await GetSlug(PostItem.Id, PostItem.Title); var item = await _db.BlogPosts.SaveItem(PostItem); PostItem = item; Message = Resources.Saved; return(Redirect($"~/Admin/Posts/Edit?id={PostItem.Id}")); } } return(Page()); }
async Task ImportPost(PostItem post) { await ImportImages(post); await ImportFiles(post); var converter = new ReverseMarkdown.Converter(); post.Content = converter.Convert(post.Content); post.Cover = AppSettings.Cover; await _db.BlogPosts.SaveItem(post); }
public async Task <Guid> AddPost(PostItem item, AuthorMapForPost author) { item.PostId = Guid.NewGuid(); item.Upvotes = 0; item.Views = 0; item.CreatedOn = DateTime.UtcNow; item.ModifiedOn = DateTime.UtcNow; item.Author = author; item.IsPublished = true; await _db.CreateDocumentAsync <PostItem>(dbName, collectionName, item); return(item.PostId); }
async Task <List <ImportMessage> > ImportFeed(StreamReader reader) { using (var xmlReader = XmlReader.Create(reader, new XmlReaderSettings() { })) { var feedReader = new RssFeedReader(xmlReader); while (await feedReader.Read()) { if (feedReader.ElementType == SyndicationElementType.Link) { var link = await feedReader.ReadLink(); _url = link.Uri.ToString(); } if (feedReader.ElementType == SyndicationElementType.Item) { try { var item = await feedReader.ReadItem(); PostItem post = new PostItem { Author = await _db.Authors.GetItem(a => a.AppUserName == _usr), Title = item.Title, Description = item.Title, Content = item.Description, Slug = await GetSlug(item.Title), Published = item.Published.DateTime, Status = SaveStatus.Publishing }; _msgs.Add(new ImportMessage { ImportType = ImportType.Post, Status = Status.Success, Message = post.Title }); await ImportPost(post); } catch (Exception ex) { _msgs.Add(new ImportMessage { ImportType = ImportType.Post, Status = Status.Error, Message = ex.Message }); } } } } return(await Task.FromResult(_msgs)); }
public async Task <ViewResult> Item(string id) { if (id.Equals("about", StringComparison.CurrentCultureIgnoreCase)) { var configSettings = new ConfigSettings(); var config = new AboutConfig(configSettings, "About", Server.MapPath("~/Settings")); config.Load(); return(View("About", config)); } if (id.Equals("guestbook", StringComparison.CurrentCultureIgnoreCase)) { return(View("Guestbook")); } var cacheKey = "post_" + id; var post = RedisManager.GetItem <Post>(cacheKey); if (post == null) { post = await _postRepository.GetPostByAlias(id); if (post != null) { RedisManager.SetItem(cacheKey, post, new TimeSpan(0, Settings.Config.CacheExpired, 0)); } } if (post != null) { var item = new PostItem { UniqueId = post.UniqueId, Title = post.Title, CategoryAlias = post.CategoryAlias, CateName = await _categoryRepository.GetNameByAlias(post.CategoryAlias), CreateTimeStr = post.CreateTime.ToString("yy-MM-dd HH:mm"), ViewCount = post.ViewCount, LabelList = JsonConvert.DeserializeObject <List <LabelShow> >(post.Labels).Select(t => t.Text).ToList(), Summary = post.Summary, Content = post.Content }; return(View(item)); } else { var error = new Elmah.Error(new Exception("文章id:" + id + " 不存在!"), System.Web.HttpContext.Current) { StatusCode = 404 }; Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(error); return(View("Error404")); } }
protected void btnSubmit_Click(object sender, EventArgs e) { if (!Page.IsValid) return; int postID = (int)ViewState["postID"]; using (MooDB db = new MooDB()) { Post post = (from p in db.Posts where p.ID == postID select p).Single<Post>(); if (post.Lock || post.Problem != null && post.Problem.LockPost) { if (!Permission.Check("post.locked.reply", false)) return; } else { if (!Permission.Check("post.reply", false)) return; } User currentUser = ((SiteUser)User.Identity).GetDBUser(db); //Send Mails SortedSet<User> userBeAt; string parsed = WikiParser.ParseAt(db, txtContent.Text, out userBeAt); foreach (User user in userBeAt) { db.Mails.AddObject(new Mail() { Title = "我@了您哦~", Content = "我在帖子[url:" + post.Name + "|../Post/?id=" + post.ID + "]中*@*了您哦~快去看看!\r\n\r\n*原文如下*:\r\n" + parsed, From = currentUser, To = user, IsRead = false }); } PostItem postItem = new PostItem() { Post = post, Content = txtContent.Text, CreatedBy = currentUser }; db.PostItems.AddObject(postItem); db.SaveChanges(); Logger.Info(db, string.Format("创建帖子#{0}的新项#{1}", post.ID, postItem.ID)); } PageUtil.Redirect("回复成功", "~/Post/?id=" + postID); }
public async Task <IActionResult> Post([FromRoute] Guid basketId, [FromBody] PostItem requestItem) { var request = new CreateItemRequest { BasketId = basketId, Item = requestItem }; var item = await _mediator.Send(request); if (item == null) { return(BadRequest()); } return(CreatedAtAction("Get", new { basketId = basketId, id = item.Id }, item)); }
//public class PostListItem //{ // public int Id { get; set; } // public string Text { get; set; } // public virtual ApplicationUser From { get; set; } // public virtual ApplicationUser To { get; set; } //} //[HttpGet] //public List<Post> GetAll(string id) //{ // var posts = db.Posts.Where(x => x.From.Id == id); // return posts.ToList(); //} //public IHttpActionResult Get(int id) //{ // var post= db.Posts.FirstOrDefault((p) => p.Id == id); // if (post == null) // { // return NotFound(); // } // return Ok(post); //} //[HttpGet] //public List<PostListItem> List() //{ // return db.Posts.ToList() // .Select(post => new PostListItem // { // Id = post.Id, // Text = post.Text, // From = post.From, // To = post.To, // }) // .ToList(); //} public void CreatePost(PostItem newpost) { Post post = new Post { To = db.Users.Find(newpost.to), From = db.Users.Find(newpost.from), Text = newpost.text }; db.Posts.Add(post); db.SaveChanges(); //return RedirectToAction("Index", new { id = id }); }
private void FillAttachment(PostItem post) { post.Message = AttachPattern.Replace(post.Message, match => { var attachNo = match.Groups["id"].Value; if (!string.IsNullOrEmpty(attachNo) && post.Attachments != null && post.Attachments.ContainsKey(attachNo)) { var a = post.Attachments[attachNo]; return(string.Format("<img src=\"{0}\"></img>", a.url + a.attachment)); } return(""); }); }
public async Task OnGetAsync(int id) { var author = await _db.Authors.GetItem(a => a.AppUserName == User.Identity.Name); IsAdmin = author.IsAdmin; PostItem = new PostItem { Author = author, Cover = AppSettings.Cover }; if (id > 0) { PostItem = await _db.BlogPosts.GetItem(p => p.Id == id); } }
internal List <SinoPost> GetSelectedPosts() { List <SinoPost> _ret = new List <SinoPost>(); if (this.gridView1.SelectedRowsCount > 0) { int[] _selectedIndexs = this.gridView1.GetSelectedRows(); foreach (int _index in _selectedIndexs) { PostItem _item = this.gridView1.GetRow(_index) as PostItem; _ret.Add(_item.PostData); } } return(_ret); }
private void FillAttachment(PostItem post) { post.Message = AttachPattern.Replace(post.Message, match => { var attachNo = match.Groups["id"].Value; if (!string.IsNullOrEmpty(attachNo) && post.Attachments != null && post.Attachments.ContainsKey(attachNo)) { var a = post.Attachments[attachNo]; return string.Format("<img src=\"{0}\"></img>", a.url + a.attachment); } return ""; }); }
public async Task SavePostItemsTaskAsync(PostItem item) { try{ if (item.ID == null) { await postsTable.InsertAsync(item); } else { await postsTable.UpdateAsync(item); } }catch (Exception e) { Debug.WriteLine("SavePostItemsTaskAsync error: " + e.Message); } }
async Task ImportPost(PostItem post) { await ImportImages(post); await ImportFiles(post); var converter = new ReverseMarkdown.Converter(); post.Content = converter.Convert(post.Content); var blog = await _db.CustomFields.GetBlogSettings(); post.Cover = blog.Cover; await _db.BlogPosts.SaveItem(post); }
public Page1(PostItem post = null) { InitializeComponent(); DataContext = viewModel = new Page1ViewModel(); if (post == null) { viewModel.Item = PostItem.GenerateRandomList(1).First(); } else { viewModel.Item = post; } }
public async Task <ActionResult <PostItem> > Post(PostItem post) { try { post.Slug = await GetSlug(post.Id, post.Title); var saved = await _data.BlogPosts.SaveItem(post); return(Created($"admin/posts/edit?id={saved.Id}", saved)); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message)); } }
public async Task <IEnumerable <ErrorBase> > EliminarPostItem(PostItem postItem) { List <ErrorBase> errores = new List <ErrorBase>(); try { errores.AddRange(this.postValidator.Validar(postItem)); await this.postItemRepositorio.Eliminar(postItem); } catch { errores.Add(new ErrorBase(StatusCodes.Status500InternalServerError)); } return(errores); }
public IActionResult UpdatePost(int id, [FromBody] PostItem item) { if (item == null || item.Id != id) { return(BadRequest()); } var post = _blogRepository.GetPost(id); if (post == null) { return(NotFound()); } post.Image = item.Image; post.Audio = item.Audio; post.FrenchTitle = item.FrenchTitle; post.EnglishTitle = item.EnglishTitle; post.FrenchContent = item.FrenchContent; post.EnglishContent = item.EnglishContent; post.Creation = item.Creation; post.Media = item.Media; switch (post.Media) { case EnumMedia.Text: post.SpreakerEpisodeId = null; post.YoutubeVideoId = null; break; case EnumMedia.Audio: post.SpreakerEpisodeId = item.SpreakerEpisodeId; post.YoutubeVideoId = null; break; case EnumMedia.Video: post.SpreakerEpisodeId = null; post.YoutubeVideoId = item.YoutubeVideoId; break; } post.CategoryId = item.CategoryId; post.AuthorId = item.AuthorId; post.ReadingTime = item.ReadingTime; _blogRepository.UpdatePost(post); return(CreatedAtRoute("GetPost", new { id = item.Id }, item)); }
public async Task <string[]> GetReceiveNotificationUser(string PostId) { PostItem post = await this.GetById(PostId); var followList = post.UserFollows ?? new List <string>(); var commentArray = post.UserComments.ToArray(); foreach (var item in commentArray) { if (!followList.Any(x => x == item)) { followList.Add(item); } } return(followList.ToArray()); }
internal async Task UpdateItemData(string message) { uint MaxId = 0; try { MaxId = (await _connection.Table <PostItem>().ToListAsync()).Max(x => x.ID); } catch { } PostItem newPost = new PostItem { ID = MaxId + 1, Content = message }; await _connection.InsertAsync(newPost); }
private void BuildContent(PostItem post, S1PostItem item) { post.Message = post.Message ?? ""; //work around post.Message = post.Message.Replace("<imgwidth=", "<img width=").Replace("\n", ""); FillAttachment(post); var content = new HtmlDoc(string.Format("<div>{0}</div>", S1Resource.HttpUtility.HtmlDecode(post.Message))) .RootElement; if (content != null) item.AddRange(SimpleParser.SimpleThreadParser.ReGroupContent(content)); }
private void CallbackChannelID(PostItem postItem) { string hTML = postItem.Post.HTML; HtmlDocument htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(hTML); foreach (HtmlNode htmlNode in (IEnumerable <HtmlNode>)htmlDocument.DocumentNode.SelectNodes("//meta")) { if (!htmlNode.Attributes.Contains("itemprop") || !htmlNode.Attributes["itemprop"].Value.Contains("channelId") || !htmlNode.Attributes.Contains("content")) { continue; } this._channelID = htmlNode.Attributes["content"].Value; } this.GetPage(1); }
private void GetPageCallbackToken(PostItem obj) { HtmlDocument htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(obj.Post.HTML); foreach (HtmlNode htmlNode in (IEnumerable <HtmlNode>)htmlDocument.DocumentNode.SelectNodes("//meta")) { if (!htmlNode.Attributes.Contains("name") || !(htmlNode.Attributes["name"].Value == "csrf-token")) { continue; } this._token = htmlNode.Attributes["content"].Value; this._token = Uri.EscapeDataString(this._token); } this.GetPage(10); }
protected Item BindItem(Item item, ExchangeService service, PropertySet propertySet) { if (item.GetType() == typeof(Microsoft.Exchange.WebServices.Data.Appointment)) { return(Appointment.Bind(service, item.Id, propertySet)); } else if (item.GetType() == typeof(Microsoft.Exchange.WebServices.Data.Task)) { return(Task.Bind(service, item.Id, propertySet)); } else if (item.GetType() == typeof(Microsoft.Exchange.WebServices.Data.Contact)) { return(Contact.Bind(service, item.Id, propertySet)); } else if (item.GetType() == typeof(Microsoft.Exchange.WebServices.Data.ContactGroup)) { return(ContactGroup.Bind(service, item.Id, propertySet)); } else if (item.GetType() == typeof(Microsoft.Exchange.WebServices.Data.PostItem)) { return(PostItem.Bind(service, item.Id, propertySet)); } else if (item.GetType() == typeof(Microsoft.Exchange.WebServices.Data.MeetingCancellation)) { return(MeetingCancellation.Bind(service, item.Id, propertySet)); } else if (item.GetType() == typeof(Microsoft.Exchange.WebServices.Data.MeetingRequest)) { return(MeetingRequest.Bind(service, item.Id, propertySet)); } else if (item.GetType() == typeof(Microsoft.Exchange.WebServices.Data.MeetingResponse)) { return(MeetingResponse.Bind(service, item.Id, propertySet)); } else if (item.GetType() == typeof(Microsoft.Exchange.WebServices.Data.MeetingMessage)) { return(MeetingMessage.Bind(service, item.Id, propertySet)); } else if (item.GetType() == typeof(Microsoft.Exchange.WebServices.Data.EmailMessage)) { return(EmailMessage.Bind(service, item.Id, propertySet)); } else { throw new Exception("Unknown Exchange Item type: " + item.GetType().FullName); } }
/// <summary> /// Get post converted to Json /// </summary> /// <param name="post">Post</param> /// <returns>Json post</returns> public PostItem GetPost(Post post) { var categories = _ctx.PostsInCategories.Where(m => m.PostsId == post.Id).Select(m => m.Categories).ToList(); var author = new Author(); author.Id = post.Author?.Id; author.Avatar = post.Author?.Avatar; author.Signature = post.Author?.Signature; author.DisplayName = post.Author?.DisplayName; author.Name = post.Author?.UserName; var postitem = new PostItem { Id = post.Id, Author = author, Title = post.Title, Content = post.Content, Slug = post.Slug, RelativeLink = "/post/" + post.Id, CommentsCount = post.Comments != null ? post.Comments.Count : 0, ReadCount = post.ReadCount, DatePublished = post.DatePublished, DateCreated = post.DatePublished.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture), Categories = GetCategories(categories), Tags = GetTags(post.Tags.Split(',')), Comments = GetComments(post), IsPublished = post.IsPublished, }; if (!string.IsNullOrEmpty(post.CoverImage)) { var covers = Newtonsoft.Json.JsonConvert.DeserializeObject <List <string> >(post.CoverImage); //TODO if (covers.Count > 0) { postitem.Cover1 = covers[0]; } if (covers.Count > 1) { postitem.Cover2 = covers[1]; } if (covers.Count > 2) { postitem.Cover2 = covers[2]; } } return(postitem); }
protected override async Task OnInitializedAsync() { if (PostId > 0) { Post = await DataService.BlogPosts.GetItem(p => p.Id == PostId); } else { var blog = await DataService.CustomFields.GetBlogSettings(); Post = new PostItem { Cover = blog.Cover, Content = "", Title = "" }; } Cover = $"background-image: url({AppSettings.SiteRoot}{Post.Cover})"; StateHasChanged(); }
/// <summary> /// The get post items. /// </summary> /// <param name="postList"> /// The post list. /// </param> /// <param name="rootUrl"> /// The root url. /// </param> /// <returns> /// The <see cref="List{PostItem}"/>. /// </returns> private static List <PostItem> GetPostItems(List <PostEntity> postList, string rootUrl) { string url = rootUrl.TrimEnd('/'); var postItems = new List <PostItem>(); postList.ForEach( post => { var postModel = new PostItem { Post = post, RootUrl = url }; postItems.Add(postModel); }); return(postItems); }
protected void btnSubmit_Click(object sender, EventArgs e) { if (!Page.IsValid) return; int postID; int? problemID = (int?)ViewState["problemID"]; using (MooDB db = new MooDB()) { problem = problemID == null ? null : (from p in db.Problems where p.ID == problemID select p).Single<Problem>(); if (problem != null) { if (problem.LockPost) { if (!Permission.Check("post.locked.create", false)) return; } else { if (!Permission.Check("post.create", false)) return; } } else { if (!Permission.Check("post.create", false)) return; } User currentUser = ((SiteUser)User.Identity).GetDBUser(db); Post post = new Post() { Name = txtName.Text, Problem = problem, Lock = false }; db.Posts.AddObject(post); db.SaveChanges(); //Send Mails SortedSet<User> userBeAt; string parsed = WikiParser.ParseAt(db, txtContent.Text, out userBeAt); foreach (User user in userBeAt) { db.Mails.AddObject(new Mail() { Title = "我@了您哦~", Content = "我新建了帖子[url:" + post.Name + "|../Post/?id=" + post.ID + "],并在其中*@*了您哦~快去看看!\r\n\r\n*原文如下*:\r\n" + parsed, From = currentUser, To = user, IsRead = false }); } PostItem item = new PostItem() { Post = post, Content = txtContent.Text, CreatedBy = currentUser }; db.PostItems.AddObject(item); db.SaveChanges(); postID = post.ID; Logger.Info(db, "创建帖子#" + postID); } PageUtil.Redirect("创建成功", "~/Post/?id=" + postID); }
public static void HttpMultipart(HttpWebRequest request, Hashtable data, Hashtable files) { // We have files, so use the more complex multipart encoding. string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x")); request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary); ArrayList items = new ArrayList(); // Determine the amount of data we will be sending long length = 0; foreach (string key in data.Keys) { PostItem item = new PostItem(key, data[key].ToString(), boundary); items.Add(item); length += item.Length; } foreach (string key in files.Keys) { PostFile file = new PostFile(key, (FileInfo)files[key], boundary); items.Add(file); length += file.Length; } length += boundary.Length + 8; request.ContentLength = length; // Now stream the data. //using (Stream requestStream = File.Create("c:\\Users\\bneely\\documents\\debug.txt")) using (Stream requestStream = request.GetRequestStream()) { foreach (PostItem item in items) { requestStream.Write(item.Header, 0, item.Header.Length); if (item.GetType() == typeof(PostFile)) { FileStream fileData = ((PostFile)item).OpenRead(); byte[] buffer = new byte[32768]; int read = 0; while ((read = fileData.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, read); } } else { byte[] itemData = UTF8Encoding.UTF8.GetBytes(item.Data); requestStream.Write(itemData, 0, itemData.Length); } byte[] end = UTF8Encoding.UTF8.GetBytes(string.Format("\r\n--{0}--\r\n", boundary)); requestStream.Write(end, 0, end.Length); } } }
private void Post() { Affect affect; foreach (string name in Items_Post.Keys) { PostItem postItem = new PostItem(); postItem.Name = name; postItem.PostAffect = ""; postItem.Amount = Items_Post[name]; postItem.CategoryId = items_Category[name]; if (items_Describe.Keys.Contains(name)) { postItem.Describe = items_Describe[name]; } else { postItem.Describe = ""; } postItem.UserId = (App.Current as App).UserId; if (Items_Image.Keys.Contains(name)) { postItem.PostImage = Helper.StreamToBytes(Items_Image[name]); } else { } if (!Constant.getDictionary_Affect().ContainsKey(name)) { affect = Constant.getDictionary_Affect()["other"]; } else { affect = Constant.getDictionary_Affect()[name]; } postItem.GetPoints = (int)Math.Round(2 * affect.carbon_emissions, 0); if (affect.carbon_emissions != 0) { postItem.PostAffect += "reduce " + affect.carbon_emissions * Items_Post[name] +" kg of carbon emissions"; } if (affect.electricity != 0) { postItem.PostAffect += "save " + affect.electricity * Items_Post[name] + " kWh of electricity!"; } if (affect.forest != 0) { postItem.PostAffect += "prevent " + affect.forest * Items_Post[name] + " m² of forest from being destory!!"; } if (affect.gasoline != 0) { postItem.PostAffect += "save " + affect.gasoline * Items_Post[name] + " litres of gasoline!"; } if (affect.soil != 0) { postItem.PostAffect += "prevent " + affect.soil * Items_Post[name] + " m³ of soil from being polluted!"; } if (affect.water != 0) { postItem.PostAffect += "prevent " + affect.water * Items_Post[name] + " m³ of water from being polluted!"; } shareContent += postItem.PostAffect; client.PostAsync(postItem); } }