public ActionResult Update(PostInput input) { if (!ModelState.IsValid) return View("Edit", input); var post = RavenSession.Load<Post>(input.Id) ?? new Post {CreatedAt = DateTimeOffset.Now}; input.MapPropertiesToInstance(post); // Be able to record the user making the actual post var user = RavenSession.GetCurrentUser(); if (string.IsNullOrEmpty(post.AuthorId)) { post.AuthorId = user.Id; } else { post.LastEditedByUserId = user.Id; post.LastEditedAt = DateTimeOffset.Now; } if (post.PublishAt == DateTimeOffset.MinValue) { var postScheduleringStrategy = new PostSchedulingStrategy(RavenSession, DateTimeOffset.Now); post.PublishAt = postScheduleringStrategy.Schedule(); } // Actually save the post now RavenSession.Store(post); if (input.IsNewPost()) { // Create the post comments object and link between it and the post var comments = new PostComments { Comments = new List<PostComments.Comment>(), Spam = new List<PostComments.Comment>(), Post = new PostComments.PostReference { Id = post.Id, PublishAt = post.PublishAt, } }; RavenSession.Store(comments); post.CommentsId = comments.Id; } return RedirectToAction("Details", new {Id = post.MapTo<PostReference>().DomainId}); }
public ActionResult Add(PostInput input) { if (!ModelState.IsValid) return View("Edit", input); // Be able to record the user making the actual post var user = RavenSession.GetCurrentUser(); // Create the post comments object and link between it and the post var comments = new PostComments { Comments = new List<PostComments.Comment>(), Spam = new List<PostComments.Comment>() }; RavenSession.Store(comments); // Create new post object var post = new Post { Tags = TagsResolver.ResolveTagsInput(input.Tags), PublishAt = input.PublishAt, AllowComments = input.AllowComments, AuthorId = user.Id, LastEditedByUserId = user.Id, LastEditedAt = DateTimeOffset.Now, CommentsId = comments.Id, ContentType = input.ContentType, Body = input.Body, CreatedAt = DateTimeOffset.Now, Title = input.Title, }; if (post.PublishAt == DateTimeOffset.MinValue) { var postScheduleringStrategy = new PostSchedulingStrategy(RavenSession, DateTimeOffset.Now); post.PublishAt = postScheduleringStrategy.Schedule(); } // Actually save the post now RavenSession.Store(post); comments.Post = new PostComments.PostReference { Id = post.Id, PublishAt = post.PublishAt, }; return RedirectToAction("Details", new { id = post.Id.ToIntId() }); }
public ActionResult AddPost(PostInput item) { var context = new ElContext(); var post = new Post(); post.Title = item.Title; post.Text = item.Text; post.DateTime = DateTime.Now; post.Active = true; var guid = Guid.NewGuid(); item.Image.SaveAs(HttpContext.Server.MapPath("~/Content/" + guid + ".jpg")); post.Images.Add(new Image { Path = "Content/" + guid + ".jpg", PostId = post.Id }); context.Posts.Add(post); context.SaveChanges(); return RedirectToAction("Index"); }
/// <summary> /// /// </summary> public async Task <PublicJsonResult> CreateAsync(PostInput input) { //بررسی یکتا بودن عنوان مطلب var existPost = await _postRepository.GetByTitleAsync(input.Title.Trim()); if (existPost != null) { return new PublicJsonResult { result = false, message = Messages.Post_Title_Already_Exist } } ; //بررسی نامک -- url friendly input.UrlTitle = input.UrlTitle.IsNullOrEmptyOrWhiteSpace() ? input.Title.GenerateUrlTitle() : input.UrlTitle.GenerateUrlTitle(); var post = new Post { Title = input.Title, Author = input.Author, Content = input.Content, CreateDateTime = DateTime.Now, ModifiedDateTime = DateTime.Now, PostLevel = input.PostLevel, MetaDescription = input.MetaDescription, MetaKeyWords = input.MetaKeyWords, PublishDateTime = input.PublishDateTime, PublishStatus = input.PublishStatus, MetaRobots = input.MetaRobots, UrlTitle = input.UrlTitle, UserId = input.UserId, CategoryIds = AddTagsToPost(input.Categories), TagIds = await AddTagsToPostAsync(input.Tags), }; await _postRepository.CreateAsync(post); return(new PublicJsonResult { result = true, id = post.Id, message = Messages.Post_Create_Success }); }
public ModelResult <Post> AddPost(PostInput postInput, EntityState postState) { postInput = pluginEngine.Process <PluginPostInput>("ProcessInputOfPost", new PluginPostInput(postInput)).ToPostInput(); postInput = pluginEngine.Process <PluginPostInput>("ProcessInputOfPostOnAdd", new PluginPostInput(postInput)).ToPostInput(); ModelResult <Post> results = addPost(postInput, () => postInput.ToPost(postState, context.User.Cast <User>(), t => expressions.Clean("TagReplace", t))); if (results.IsValid) { Post newPost = results.Item; string postUrl = urlHelper.AbsolutePath(urlHelper.Post(newPost)); //TODO: (erikpo) Move this into a module addCreatorSubscription(newPost); //TODO: (erikpo) Move this into a module if (newPost.State == EntityState.Normal && newPost.Published.HasValue) { IEnumerable <TrackbackOutbound> trackbacksToAdd = extractTrackbacks(newPost, postUrl, newPost.Blog.DisplayName); IEnumerable <TrackbackOutbound> unsentTrackbacks = trackbackOutboundRepository.GetUnsent(newPost.ID); IEnumerable <TrackbackOutbound> trackbacksToRemove = trackbacksToAdd.Where(tb => !unsentTrackbacks.Contains(tb) && !tb.Sent.HasValue); trackbackOutboundRepository.Remove(trackbacksToRemove); trackbackOutboundRepository.Save(trackbacksToAdd); } else { //TODO: (erikpo) Remove all outbound trackbacks } pluginEngine.ExecuteAll("PostSaved", new { context, post = new PostReadOnly(newPost, postUrl) }); pluginEngine.ExecuteAll("PostAdded", new { context, post = new PostReadOnly(newPost, postUrl) }); if (newPost.State == EntityState.Normal && newPost.Published.HasValue && newPost.Published.Value <= DateTime.UtcNow) { pluginEngine.ExecuteAll("PostPublished", new { context, post = new PostReadOnly(newPost, postUrl) }); } } return(results); }
public async Task <PostOutput> UpdatePost(PostInput updatePostDto) { if (updatePostDto.Id == Guid.Empty) { throw new Exception("帖子Id不可以为空"); } var post = await _postRepository.GetAsync(updatePostDto.Id); post.Update(updatePostDto.Title, updatePostDto.Content); var updatedPost = await _postRepository.UpdateAsync(post); var user = await _userRepository.GetAsync(post.AuthorId); var postDto = updatedPost.MapTo <PostOutput>(); Mapper.Map(user, postDto); return(postDto); }
[UnitOfWork] //TODO: Will be removed when we implement action filter public virtual async Task <IActionResult> OnPostAsync(PostInput input, string returnUrl = "", string returnUrlHash = "") { ReturnUrl = returnUrl; ReturnUrlHash = returnUrl; ValidateModel(); var result = await _signInManager.PasswordSignInAsync( input.UserNameOrEmailAddress, input.Password, input.RememberMe, true ); if (!result.Succeeded) { throw new UserFriendlyException("Login failed!"); //TODO: Handle other cases, do not throw exception } return(RedirectSafely(returnUrl, returnUrlHash)); }
public async Task <IActionResult> CrearPost(PostInput post) { if (!ModelState.IsValid) { RedirectToAction("Ver", null); } if (!String.IsNullOrEmpty(post.ImagenPost?.FileName)) { string wwwRoothRuta = _hostEnvironment.WebRootPath; string nombreArchivo = Path.GetFileNameWithoutExtension(post.ImagenPost.FileName); string extension = Path.GetExtension(post.ImagenPost.FileName); nombreArchivo = nombreArchivo + DateTime.Now.ToString("yymmssfff") + extension; post.URLImagen = nombreArchivo; string ruta = Path.Combine(wwwRoothRuta + "\\img", nombreArchivo); using (var fileStream = new FileStream(ruta, FileMode.Create)) { await post.ImagenPost.CopyToAsync(fileStream); } } var postDB = new Post { Contenido = post.Contenido, Fecha = DateTime.Now, URLImagen = post.URLImagen, UserId = post.UserId }; await _context.Post.AddAsync(postDB); await _context.SaveChangesAsync(); return(RedirectToAction("Ver")); // return Content($"userid: {post?.UserId} fecha: {postDB?.Fecha} contenido: {post?.Contenido} url: {post?.URLImagen}"); }
public async Task CreatePost_Test_Count_Should_Increment() { //Arrange var countBefore = UsingDbContext(a => a.Post.Count()); PostInput postDto = new PostInput() { AuthorId = UsingDbContext <User>(a => a.User.FirstOrDefault()).Id, Content = "HI", Title = "title5" }; //Act var flag = await _postAppService.CreatePost(postDto); var count = UsingDbContext(a => a.Post.Count()); //Assert Assert.NotNull(flag); Assert.Equal(countBefore + 1, count); this.Dispose(); }
public async Task <string> Create(PostInput postInput) { using (HttpClient client = new HttpClient()) { using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URL + string.Format("createPost"))) { var values = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("AuthorId", postInput.AuthorId.ToString()), new KeyValuePair <string, string>("Title", postInput.Title), new KeyValuePair <string, string>("Content", postInput.Content), }; request.Content = new FormUrlEncodedContent(values); using (HttpResponseMessage response = await client.SendAsync(request)) { response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsStringAsync(); return(result); } } } }
public DataTransfer <PostOutput> Insert(PostInput Input) { DataTransfer <PostOutput> transer = new DataTransfer <PostOutput>(); IList <string> errors = Validator.Validate(Input); if (errors.Count == 0) { PerformanceStatistic performancestatistic = new PerformanceStatistic(); PostOutput output = new PostOutput(); performancestatistic.CopyFrom(Input); performancestatistic = _iPerformanceStatisticRepository.InsertPerformanceStatistic(performancestatistic); output.CopyFrom(performancestatistic); transer.IsSuccess = true; transer.Data = output; } else { transer.IsSuccess = false; transer.Errors = errors.ToArray <string>(); } return(transer); }
[UnitOfWork] //TODO: Will be removed when we implement action filter public virtual async Task <IActionResult> OnPostAsync(PostInput input, string returnUrl = "", string returnUrlHash = "") { if (!ModelState.IsValid) { throw new NotImplementedException(); } var user = new IdentityUser(GuidGenerator.Create(), input.UserName, CurrentTenant.Id); var result = await _userManager.CreateAsync(user, input.Password); if (!result.Succeeded) { throw new NotImplementedException(); } await _userManager.SetEmailAsync(user, input.EmailAddress); await _signInManager.SignInAsync(user, isPersistent : false); //TODO: Use LocalRedirect and Url.GetLocalUrl methods instead of a custom one! return(RedirectSafely(returnUrl, returnUrlHash)); }
public HttpResponseMessage Post(PostInput input) { try { if (string.IsNullOrEmpty(input.Name)) { throw new Exception("name is empty"); } var insertResult = this.repo.Insert(Account.GenerateInstance(input.Name)); if (!insertResult) { throw new Exception($"the name:{input.Name} insert to repo fail"); } return(this.Request.CreateResponse(HttpStatusCode.OK)); } catch (Exception ex) { Console.WriteLine(ex.Message); return(this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message)); } }
public ActionResult Edit(PostInput input, int id) { if (!ModelState.IsValid) return View("Edit", input); var post = RavenSession.Load<Post>(id) ?? new Post(); input.MapPropertiesToInstance(post); var user = RavenSession.GetCurrentUser(); if (string.IsNullOrEmpty(post.AuthorId)) { post.AuthorId = user.Id; } else { post.LastEditedByUserId = user.Id; post.LastEditedAt = DateTimeOffset.Now; } RavenSession.Store(post); var postReference = post.MapTo<PostReference>(); return RedirectToAction("Details", new { Id = postReference.DomainId, postReference.Slug}); }
public OxiteViewModelItem <PostInput> Add(Blog blog, PostInput postInput) { //TODO: (erikpo) Check permissions return(new OxiteViewModelItem <PostInput>(new PostInput(blog, postInput))); }
public DataTransfer <PostOutput> Insert(PostInput Input) { throw new NotImplementedException(); }
// POST api/<controller> public IHttpActionResult Post([FromBody] PostInput data) { Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB"); if (data.Keywords == null) { data.Keywords = new string[0]; } List <string> addkeywords = new List <string>(); foreach (string key in data.Keywords) { string[] ks = key.Split(' '); if (ks.Length == 2) { addkeywords.AddRange(ks); } if (ks.Length > 2) { addkeywords.AddRange(ks.Zip(ks.Skip(1), (x, y) => x + " " + y)); } } data.Keywords = data.Keywords.Concat(addkeywords).ToArray(); (Coordinate[] coordinates, string[] cities) = ApiInterface.GetHotelLocations(data); var parser = new Chronic.Parser(); if (data.ArrivalDate == null || data.ArrivalDate == "") { data.ArrivalDate = "today"; } if (data.DepartureDate == null || data.DepartureDate == "") { data.DepartureDate = "next week"; } if (data.Image == null) { data.Image = ""; } var opt = new Chronic.Options(); opt.EndianPrecedence = Chronic.EndianPrecedence.Little; DateTime arrivalDate; DateTime departureDate; if (data.ArrivalDate != null) { data.ArrivalDate.Replace('.', '/'); } if (data.DepartureDate != null) { data.DepartureDate.Replace('.', '/'); } try { arrivalDate = DateTime.Parse(data.ArrivalDate, null); } catch { arrivalDate = parser.Parse(data.ArrivalDate, opt).Start.Value; } try { departureDate = DateTime.Parse(data.DepartureDate, null); } catch { departureDate = parser.Parse(data.DepartureDate, opt).Start.Value; } Hotel[] hotels = coordinates.SelectMany(x => ApiInterface.Check24(x.lat, x.lng, arrivalDate, departureDate)).ToArray(); hotels = hotels.Where((x, i) => !hotels.Take(i).Any(y => y.Id == x.Id)).ToArray(); return(Ok(new { Hotels = hotels.Take(data.MaxOutputSize), Coordinates = coordinates, Cities = cities })); }
public ModelResult <Post> EditPost(PostAddress postAddress, PostInput postInput, EntityState state, User creator) { return(new ModelResult <Post>(new ValidationStateDictionary(typeof(PostInput), new ValidationState()))); }
public IActionResult AddPostPage(PostInput input) { return(View("Add")); }