public async Task <IActionResult> Edit(Guid id, PostDataModel postDataModel, IFormFile formFile) { var post = await this.postRepository.GetById(id); if (ModelState.IsValid) { if (post != null) { post.Title = postDataModel.Title; post.Preview = postDataModel.Preview; post.Content = postDataModel.Content; post.Modified = DateTime.Now; post.Link = postDataModel.Link; if (formFile != null) { post.Cover = formFile.ToByteArray(); } } await this.postRepository.Update(post); return(this.RedirectToAsync <BlogController>(x => x.View(post.BlogId.Value))); } postDataModel.Title = post.Title; postDataModel.Content = post.Content; postDataModel.Cover = post.Cover; return(View(postDataModel)); }
public ActionResult GetPending(int page = 1, int size = 10, string search = "") { int total; IQueryable <Post> temp; if (string.IsNullOrEmpty(search)) { temp = PostBll.LoadPageEntitiesNoTracking(page, size, out total, p => p.Status == Status.Pending, p => p.Id); } else { temp = PostBll.LoadPageEntitiesNoTracking(page, size, out total, p => p.Status == Status.Pending && (p.Title.Contains(search) || p.Author.Contains(search) || p.Email.Contains(search) || p.Label.Contains(search)), p => p.Id); } var plist = temp.OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.ModifyDate).Select(p => new { p.Id, p.Author, CategoryName = p.Category.Name, p.Email, p.IsFixedTop, p.Label, md = p.ModifyDate, pd = p.PostDate, p.Title, ViewCount = p.PostAccessRecord.Any() ? p.PostAccessRecord.Sum(r => r.ClickCount) : 1, p.VoteDownCount, p.VoteUpCount, stat = p.Status }).ToList(); var list = new List <PostDataModel>(); plist.ForEach(item => { PostDataModel model = item.MapTo <PostDataModel>(); model.PostDate = item.pd.ToString("yyyy-MM-dd HH:mm"); model.ModifyDate = item.md.ToString("yyyy-MM-dd HH:mm"); model.Status = item.stat.GetDisplay(); list.Add(model); }); var pageCount = Math.Ceiling(total * 1.0 / size).ToInt32(); return(PageResult(list, pageCount, total)); }
public async Task <IActionResult> New(int id, string CommentText) { if (string.IsNullOrWhiteSpace(CommentText)) { ModelState.AddModelError("", "Text field is required!"); return(RedirectToAction("Details", "Post", new { id })); } PostDataModel postDataModel = this.applicationContext.Posts.FirstOrDefault(c => c.PostId == id); ApplicationUser currentUser = this.applicationContext.Users.FirstOrDefault(u => u.Id == this.User.FindFirstValue(ClaimTypes.NameIdentifier)); if (postDataModel.Archieved == true) { return(RedirectToAction("Details", "Post", new { id })); } CommentDataModel comment = new CommentDataModel { Content = CommentText, UploadDate = DateTime.Now, Author = currentUser, Post = postDataModel }; this.applicationContext.Comments.Add(comment); await this.applicationContext.SaveChangesAsync(); return(RedirectToAction("Details", "Post", new { id })); }
private ICollection <Tag> GetTagsFromDataModel(PostDataModel postData) { // get the tags from the string var tags = new List <Tag>(); if (!string.IsNullOrWhiteSpace(postData.Tags)) { tags = postData.Tags.Split(',').Select(t => new Tag { Name = t.Trim() }).ToList(); } // add the new tags to the database for (var i = 0; i < tags.Count; i++) { var currentTag = tags[i]; var existingTag = this.data.Tags.Find(t => t.Name == currentTag.Name).FirstOrDefault(); if (existingTag != null) { tags[i] = existingTag; } else { this.data.Tags.Add(tags[i]); } } return(tags); }
/// <summary> /// 获取所有文章 /// </summary> /// <returns></returns> public ActionResult GetAllData() { var plist = PostService.LoadEntitiesNoTracking(p => p.Status != Status.Deleted).OrderBy(p => p.Status).ThenByDescending(p => p.IsFixedTop).ThenByDescending(p => p.ModifyDate).Select(p => new { p.Id, p.Author, CategoryName = p.Category.Name, p.Email, p.IsFixedTop, p.Label, md = p.ModifyDate, pd = p.PostDate, p.Title, ViewCount = p.TotalViewCount, p.VoteDownCount, p.VoteUpCount, stat = p.Status }).ToList(); var list = new List <PostDataModel>(); plist.ForEach(item => { PostDataModel model = item.MapTo <PostDataModel>(); model.PostDate = item.pd.ToString("yyyy-MM-dd HH:mm"); model.ModifyDate = item.md.ToString("yyyy-MM-dd HH:mm"); model.Status = item.stat.GetDisplay(); list.Add(model); }); return(ResultData(list)); }
public ActionResult Index(int ID) { ArticleModel model = new ArticleModel(); try { PostDataModel article = dbConnect.GetArticleByID(ID); if (article != null) { model.Post = article; model.Scrums = Uti.CreateScrums(Url, article); model.RelatePosts = dbConnect.GetRelatePost(article); } else { // Error return(RedirectToAction("Index", "Error", new { action = "Index", controller = "Article", errorMessage = "Post isn't existed" })); } return(View(model)); } catch (Exception ex) { return(RedirectToAction("Index", "Error", new { action = "Index", controller = "Article", errorMessage = ex.Message })); } }
public void TestFluentMap() { PostDataModel postData = null; routes.ShouldMap("/frombody/post/123"). To <FromBodyController>(c => c.Post(123, postData)); }
public async Task <IActionResult> Steal(Guid id, string WebsiteUrl) { PostDataModel postDataModel = new PostDataModel { Title = WebsiteUrl, Link = WebsiteUrl, BlogId = id, AuthorId = User.Identity.GetAuthorId() }; var request = WebRequest.Create(WebsiteUrl) as HttpWebRequest; var response = request.GetResponse() as HttpWebResponse; if (response.StatusCode == HttpStatusCode.OK) { var receiveStream = response.GetResponseStream(); var readStream = StreamReader.Null; readStream = response.CharacterSet == null ? new StreamReader(receiveStream) : new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet)); postDataModel.Content = readStream.ReadToEnd(); response.Close(); readStream.Close(); } await this.postRepository.Add(postDataModel); return(this.RedirectToAsync <BlogController>(x => x.View(id))); }
public async Task <ActionResult> Create(PostBindingModel post) { var model = new PostDataModel() { Titulo = post.Titulo, Descricao = post.Descricao, PerfilId = post.PerfilId }; try { HttpFileCollectionBase files = Request.Files; int fileCount = files.Count; await _blobHelper.SetupCloudBlob(connectionString); var blob = _blobHelper._blobCointainer.GetBlockBlobReference(_blobHelper.GetRandomBlobName(files[0].FileName)); await blob.UploadFromStreamAsync(files[0].InputStream); model.Foto = blob.StorageUri.PrimaryUri.ToString(); await _clientHelper.PostPostAsync(model); return(RedirectToAction("Index")); } catch { return(View()); } }
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { if (bindingContext.ModelType != typeof(PostDataModel)) { return(false); } try { // Get the content of the request, deserialize into your model object Task <string> bodyTask = actionContext.Request.Content.ReadAsStringAsync(); PostDataModel vm = JsonConvert.DeserializeObject <PostDataModel>(bodyTask.Result); // Retrieve your metadata from your controller. In order to know it is there, have your controller implement an interface with a Metadata property that is accessible. // Your code shows it as private, you'll need to loosen that up so the ModelBinder has access var metadata = ((IMetadata)actionContext.ControllerContext.Controller).Metadata; // do stuff with metadata to validate your object however you wish vm.PopulateValidationErrors(); // return true if you were able to deserialize this object, false if you couldn't return(vm != null); } catch { // do logging return(false); } }
public IActionResult Edit(int id, PostDataModel postDataModel, IFormFile _formFile) { PostDataModel post = AutoInclude.IncludeAll <PostDataModel>(this.applicationContext.Posts).FirstOrDefault(bp => bp.PostId == id); if (ModelState.IsValid) { if (post != null) { post.Title = postDataModel.Title; post.Preview = postDataModel.Preview; post.Content = postDataModel.Content; post.LastChangeDate = DateTime.Now; post.Link = postDataModel.Link; post.Tags = postDataModel.Tags; if (_formFile != null) { post.Cover = FileToByteArray(_formFile); } } this.applicationContext.Posts.Update(post); this.applicationContext.SaveChanges(); return(RedirectToAction("View", "Blog", new { id = post.Blog.BlogId })); } postDataModel.Title = post.Title; postDataModel.Content = post.Content; postDataModel.Cover = post.Cover; return(View(postDataModel)); }
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { if (bindingContext.ModelType != typeof(PostDataModel)) { return(false); } try { // Get the content of the request, deserialize into your model object Task <string> bodyTask = actionContext.Request.Content.ReadAsStringAsync(); PostDataModel vm = JsonConvert.DeserializeObject <PostDataModel>(bodyTask.Result); // Get an instance of your IService and get metadata var service = (IService)actionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(IService)); var metadata = service.GetMetadata(); // this is how you would get the Metadata directly from your controller as long as it was accessible //var metadata = ((IMetadata)actionContext.ControllerContext.Controller).Metadata; // do stuff with metadata to validate your object however you wish vm.PopulateValidationErrors(); // return true if you were able to deserialize this object, false if you couldn't return(vm != null); } catch { // do logging return(false); } }
public void TestFluentMap() { PostDataModel postData = null; config.ShouldMap("/api/frombody/123"). To <FromBodyController>(HttpMethod.Post, c => c.CreateSomething(123, postData)); }
/// <summary> /// Create list scrums /// </summary> /// <param name="url"></param> /// <param name="post"></param> /// <returns></returns> public static List <ScrumData> CreateScrums(System.Web.Mvc.UrlHelper url, PostDataModel post) { List <ScrumData> scrums = new List <ScrumData>(); if (post == null || url == null) { return(scrums); } // Add Home page ScrumData homePage = new ScrumData() { Link = url.Action("Index", "Home"), Name = "Trang Chủ" }; scrums.Add(homePage); // Add link catalogic ScrumData cataPage = new ScrumData() { Link = url.Action("Index", "Home"), Name = post.CatalogicName }; scrums.Add(cataPage); // Add Post ScrumData postText = new ScrumData() { Link = string.Empty, Name = post.Title }; scrums.Add(postText); return(scrums); }
public IHttpActionResult Update(PostDataModel postData) { if (postData == null || postData.Id == null) { return(this.BadRequest("You must provide a valid post id and a new content.")); } var post = this.data.Posts.GetById(postData.Id); if (post == null) { return(this.BadRequest("Invalid post id.")); } if (!string.IsNullOrWhiteSpace(postData.Content)) { post.Content = postData.Content; } if (!string.IsNullOrWhiteSpace(postData.Tags)) { var newTags = this.GetTagsFromDataModel(postData); post.Tags = newTags; } this.data.SaveChanges(); return(this.Ok()); }
public async Task <bool> UpdateAsync(string postId, PostDataModel postData) { var post = await _unitOfWork.Posts.GetByIdAsync(postId); post.Update(postData); return(await _unitOfWork.Posts.UpdateAsync(post)); }
public CreatePostDataModel Get(PostDataModel postDataModel) { var listTags = postDataModel.Tags.Select(model => model.Name); var tagsString = string.Join(",", listTags); var createPostViewModel = Mapper.Map <PostDataModel, CreatePostDataModel>(postDataModel); createPostViewModel.Tags = tagsString; return(createPostViewModel); }
public IActionResult Edit(int id) { PostDataModel target = AutoInclude.IncludeAll <PostDataModel>(this.applicationContext.Posts).FirstOrDefault(bp => bp.PostId == id); if (!(this.User.FindFirstValue(ClaimTypes.NameIdentifier).Equals(target.Author.Id) || this.User.IsInRole("Administrator"))) { return(RedirectToAction("NoAccess", "Home")); } return(View(target)); }
public string LinkTransaction(int orderID, [FromBody] PostDataModel data) { if (_database.TransferRecords(data.userID, orderID)) { return(Success(null)); } else { return(Failure()); } }
public void TestFluentMapWithFormUrlBody() { var postData = new PostDataModel { Name = "Fred Bloggers", Number = 42 }; const string PostBody = "{ Name: 'Fred Bloggers', Number: 42 }"; config.ShouldMap("/api/frombody/123").WithJsonBody(PostBody). To <FromBodyController>(HttpMethod.Post, c => c.CreateSomething(123, postData)); }
public void TestFluentMapWithFormUrlBody() { var postData = new PostDataModel { Name = "Fred Bloggers", Number = 42 }; const string PostBody = "Name=Fred+Bloggers&Number=42"; routes.ShouldMap("/frombody/post/123").WithFormUrlBody(PostBody). To <FromBodyController>(c => c.Post(123, postData)); }
public PostDataModel CreateDataModel(string request) { var postDataModel = new PostDataModel(); postDataModel.api = _verifoneSetting.ApiVersion; postDataModel.merchantid = _verifoneSetting.Merchant.MerchantId; postDataModel.systemid = _verifoneSetting.Merchant.SystemId; postDataModel.requesttype = "eftrequest"; postDataModel.requestdata = request; return(postDataModel); }
public PostWindow(CustomPost openedPost) { InitializeComponent(); // m_model = the data model (A big catch-all for all of the data) m_model = new PostDataModel(openedPost); // Model = Data Model, Just a model for your contained data. Use this Data Model DataContext = m_model; m_model.Initialize(); BrowserActions(); }
/// <summary> /// 获取文章分页 /// </summary> /// <returns></returns> public ActionResult GetPageData(int page = 1, int size = 10, OrderBy orderby = OrderBy.ModifyDate, string kw = "") { if (page < 1) { page = 1; } if (size < 1) { page = 10; } var list = new List <PostDataModel>(); IOrderedQueryable <Post> temp; var query = string.IsNullOrEmpty(kw) ? PostBll.GetAllNoTracking() : PostBll.LoadEntitiesNoTracking(p => p.Title.Contains(kw) || p.Author.Contains(kw) || p.Email.Contains(kw) || p.Label.Contains(kw) || p.Content.Contains(kw)); var total = query.Count(); var order = query.OrderByDescending(p => p.Status).ThenByDescending(p => p.IsFixedTop); switch (orderby) { case OrderBy.CommentCount: temp = order.ThenByDescending(p => p.Comment.Count); break; case OrderBy.PostDate: temp = order.ThenByDescending(p => p.PostDate); break; case OrderBy.ViewCount: temp = order.ThenByDescending(p => p.PostAccessRecord.Any() ? p.PostAccessRecord.Sum(r => r.ClickCount) : 1); break; case OrderBy.VoteCount: temp = order.ThenByDescending(p => p.VoteUpCount); break; default: temp = order.ThenByDescending(p => p.ModifyDate); break; } var plist = temp.Skip((page - 1) * size).Take(size).Select(p => new { p.Id, p.Author, CategoryName = p.Category.Name, p.Email, p.IsFixedTop, p.Label, md = p.ModifyDate, pd = p.PostDate, p.Title, ViewCount = p.PostAccessRecord.Any() ? p.PostAccessRecord.Sum(r => r.ClickCount) : 1, p.VoteDownCount, p.VoteUpCount, stat = p.Status, ModifyCount = p.PostHistoryVersion.Count }).ToList(); plist.ForEach(item => { PostDataModel model = item.MapTo <PostDataModel>(); model.PostDate = item.pd.ToString("yyyy-MM-dd HH:mm"); model.ModifyDate = item.md.ToString("yyyy-MM-dd HH:mm"); model.Status = item.stat.GetDisplay(); model.ModifyCount = item.ModifyCount; list.Add(model); }); var pageCount = Math.Ceiling(total * 1.0 / size).ToInt32(); return(PageResult(list, pageCount, total)); }
public void CreateDataModel_InitialisesModelFromConfiguration() { string requestData = "anyoldShizzle"; PostDataModel postDataModel = _createVerifonePostProcess.CreateDataModel(requestData); Assert.AreEqual(null, postDataModel.api); // ConfigurationManager.AppSettings["Verifone:PostData:Api"]; Assert.AreEqual(null, postDataModel.merchantid); // ConfigurationManager.AppSettings["Verifone:Merchant:MerchantId"] Assert.AreEqual(null, postDataModel.systemid); // ConfigurationManager.AppSettings["Verifone:Merchant:SystemId"] Assert.AreEqual("eftrequest", postDataModel.requesttype); Assert.AreEqual("anyoldShizzle", postDataModel.requestdata); Assert.Inconclusive("Unable to unit test completely. Should be taking IApplicationSettingsReader as a method parameter, so as to be able to mock config."); }
public List <InfoArticleModel> GetRelatePost(PostDataModel article) { List <InfoArticleModel> results = new List <InfoArticleModel>(); using (WebPersonalDB dbContext = new WebPersonalDB()) { #if DEBUG dbContext.Database.Log = sql => Debug.Write(sql); #endif SqlParameter numRecordParam = new SqlParameter("@NumRecord", 3); SqlParameter idArticleParam = new SqlParameter("@IDArticle", article.IDArticle); SqlParameter idCataParam = new SqlParameter("@IDCata", article.IDCata); return(dbContext.Database.SqlQuery <InfoArticleModel>("sp_GetRelateArticle @NumRecord,@IDArticle,@IDCata", numRecordParam, idArticleParam, idCataParam).ToList()); } }
public ActionResult Index() { PatOBInfo jobject = new PatOBInfo { acokey = 1, practiceid = 1, userid = "1", searchtext = "", option = 1, viewall = 1 }; ViewData["list"] = PostDataModel.PostAsyncWebApi_Test(jobject); return(View()); }
public async Task <ActionResult> NewComment(PostDataModel model) { var userName = User.Identity.GetUserName(); User user = await user_db.Users.FirstOrDefaultAsync(x => x.Login == userName); Comment newComment = new Comment { BookId = model.Number, UserId = user.Id, Text = model.Text, CreatedDate = DateTime.Now }; com_db.Comments.Add(newComment); await com_db.SaveChangesAsync(); return(View(newComment)); }
public async Task <IActionResult> CreatePost([FromRoute][ValidateGuid] string profileId, [FromBody][Required] PostDataModel data) { try { var post = await _postsService.CreateAsync(profileId, data); return(CreatedAtAction(nameof(GetPostById), "Posts", new { profileId, postId = post.Id }, post)); } catch (ItemNotFoundException) { var error = new ApiError("Profile with such Id was not found.", HttpStatusCode.NotFound); return(NotFound(error)); } }
public async Task <PostDto> CreateAsync(string profileId, PostDataModel postData) { await CheckIfProfileExists(profileId); var post = new Post() { ProfileId = new Guid(profileId), AttachedImageId = postData.AttachedImageId == null ? null : new Guid?(new Guid(postData.AttachedImageId)), Text = postData.Text, AuthorId = await GetUserId(), TimePublished = DateTime.UtcNow }; await _unitOfWork.Posts.CreateAsync(post); return(post.ToDto()); }