// To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync(IFormFile coverPhoto, IEnumerable <string> tags)
        {
            ViewData["test"] = 1;
            ModelState.Remove("Articles.CoverPhoto");
            ModelState.Remove("Articles.Id");
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            Articles.Id   = Guid.NewGuid();
            Articles.Tags = String.Join(",", tags);
            foreach (var tag in tags)
            {
                var tagCloud = _service.GetTag(tag);
                if (tagCloud != null)
                {
                    tagCloud.Amount++;
                    _service.UpdateTagToTagCloud(tagCloud);
                }
                else
                {
                    _service.AddTagToTagCloud(tag);
                }
            }

            Articles.CoverPhoto = $"http://placehold.it/750x300?text={coverPhoto.Name}";

            _service.AddArticle(Articles);
            await _service.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
예제 #2
0
        public ActionResult <ResultModel <string> > AddArticle(ArticleModel model)
        {
            model.UserId = _userManager.GetUserId(_signInManager.Context.User);

            model.OwnerId = _userManager.GetUserId(_signInManager.Context.User);
            return(_articleService.AddArticle(model));
        }
예제 #3
0
        public ActionResult Article(ArticleViewModel article)
        {
            //TryUpdateModel(article);
            if (artService.ExistByID(article.Id)) //
            {
                var mapper = new MapperConfiguration(cfg => {
                    cfg.CreateMap <ArticleViewModel, ArticleDTO> ();
                    cfg.CreateMap <TegViewModel, TegDTO>();
                }).CreateMapper();
                var articleDto = mapper.Map <ArticleViewModel, ArticleDTO>(article);

                artService.UpdateArticle(articleDto);
            }
            else
            {
                var mapper = new MapperConfiguration(cfg => {
                    cfg.CreateMap <ArticleViewModel, ArticleDTO>();
                    cfg.CreateMap <TegViewModel, TegDTO>();
                }).CreateMapper();
                var articleDto = mapper.Map <ArticleViewModel, ArticleDTO>(article);

                artService.AddArticle(articleDto);
            }



            if (article is null)
            {
                return(RedirectToAction("Index"));
            }

            return(View(article));
        }
예제 #4
0
        public async Task <IActionResult> Save(ArticleDto articleDto)
        {
            Article article = _autoMapperBase.MapToSameType <ArticleDto, Article>(articleDto);
            await _articleService.AddArticle(article);

            return(Created(string.Empty, article));
        }
예제 #5
0
 public JsonResult Add(ArticleModel model)
 {
     if (!ModelState.IsValid)
     {
         return(Json(new Result {
             success = false
         }));
     }
     Entities.ArticleInfo article = new Entities.ArticleInfo()
     {
         Title            = model.Title,
         Meta_Title       = model.Meta_Title,
         Meta_Keywords    = model.Meta_Keywords,
         Meta_Description = model.Meta_Description,
         IsRelease        = model.IsRelease,
         CategoryId       = model.CategoryId.GetValueOrDefault(),
         Content          = model.Content,
         IconUrl          = model.IconUrl,
         Id = model.Id
     };
     if (article.Id > 0)
     {
         _iArticleService.UpdateArticle(article);
     }
     else
     {
         _iArticleService.AddArticle(article);
     }
     return(Json(new Result {
         success = true
     }));
 }
예제 #6
0
        public IActionResult Post([FromBody] Article article)
        {
            logger.LogInformation("Accept POST Article");
            if (article == null)
            {
                return(BadRequest(JsonConvert.SerializeObject("invalid article object")));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                articleService.AddArticle(article);
            }
            catch (ServiceException ex)
            {
                logger.LogError(ex.Message);
                return(BadRequest(JsonConvert.SerializeObject("Server error")));
            }

            logger.LogInformation(JsonConvert.SerializeObject("Article was added from POST method"));
            return(Ok(article));
        }
예제 #7
0
        public IActionResult AddArticle([FromForm] ArticleViewModel articleViewModel)
        {
            if (!_authorService.isThereAnAuthorWithEmail(articleViewModel.Email))
            {
                return(Redirect(Url.Action("AddAuthor", "Author", articleViewModel)));
            }

            _articleService.AddArticle(articleViewModel.Email,
                                       articleViewModel.Title,
                                       articleViewModel.Content,
                                       (DateTime)articleViewModel.Date);

            String[] hashtags = articleViewModel.Hashtags.Split(" ");
            _tagsService.AddTags(hashtags);

            var recentlyCreatedArticle = _articleService.GetNewestAddedArticle(articleViewModel.Title,
                                                                               articleViewModel.Content,
                                                                               articleViewModel.Email);

            foreach (var hashtag in hashtags)
            {
                var tag = _tagsService.GetTagBy(hashtag);

                _articleTagsService.Add(tag, recentlyCreatedArticle);
            }
            return(Redirect(Url.Action("Index", "Home")));
        }
예제 #8
0
        public IActionResult Post([FromBody] ArticleModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var entity = new Article
                    {
                        Title           = model.Title,
                        Body            = model.Body,
                        AllowComments   = model.AllowComments,
                        BodyOverview    = model.BodyOverview,
                        EndDateUtc      = model.EndDateUtc,
                        StartDateUtc    = model.StartDateUtc,
                        MetaDescription = model.MetaDescription,
                        MetaKeywords    = model.MetaKeywords,
                        MetaTitle       = model.MetaTitle,
                        Tags            = model.Tags
                    };
                    _articleService.AddArticle(entity);

                    return(Ok());
                }

                return(new BadRequestResult());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
예제 #9
0
        public void AddNewArticle()
        {
            try
            {
                var article = new Article
                {
                    Title       = this.Title,
                    Description = this.Description,
                    Author      = this.Author,
                    ImageUrl    = this.ImageUrl
                };
                _articleService.AddArticle(article, CategoryIds);

                Notification = new NotificationModel("Success!", "Article successfully created", NotificationType.Success);
            }
            catch (InvalidOperationException iex)
            {
                Notification = new NotificationModel(
                    "Failed!",
                    "Failed to create article, please provide valid name",
                    NotificationType.Fail);
            }
            catch (Exception ex)
            {
                Notification = new NotificationModel(
                    "Failed!",
                    "Failed to create article, please try again",
                    NotificationType.Fail);
            }
        }
예제 #10
0
        public async Task <IActionResult> CreateArticle(CreateArticleViewModel viewModel)
        {
            if (viewModel.CreateArticleData.Title == null ||
                viewModel.CreateArticleData.Content == null ||
                viewModel.CreateArticleData.AuthorEmail == null ||
                viewModel.CreateArticleData.AuthorNickname == null ||
                viewModel.CreateArticleData.Tags == null)
            {
                _articleSubmitMessage = "Can't submit article, invalid input...";

                ViewData["Message"] = _articleSubmitMessage;

                return(View());
            }

            await _articleService.AddArticle(viewModel.CreateArticleData);

            var emailViewModel = new EmailViewModel
            {
                To      = viewModel.CreateArticleData.AuthorEmail,
                IsHtml  = false,
                Subject = "Article added...",
                Content = $"Hi { viewModel.CreateArticleData.AuthorNickname }, " +
                          $"we've sent you this confirmation email so that we can verify it's you"
            };

            await emailViewModel.SendEmail(_configuration);

            _articleSubmitMessage = "Article was submitted successfuly";

            ViewData["Message"] = _articleSubmitMessage;

            return(View());
        }
예제 #11
0
        public async Task <IActionResult> Create([Bind("CategoryId,Title,Body")] Article article)
        {
            if (ModelState.IsValid)
            {
                article.PublishDate = DateTime.Now;
                var result = await _articleService.AddArticle(article);

                return(RedirectToAction(nameof(Index)));
            }
            return(View(article));
        }
        public ActionResult <Article> Create(Article newArticle)
        {
            if (newArticle.UserName != null)
            {
                userService.AddUserByName(newArticle.UserName);

                articleService.AddArticle(newArticle);
            }

            return(CreatedAtAction(nameof(GetById), new { id = newArticle.Id }, newArticle));
        }
예제 #13
0
        public void Post([FromBody] AddArticle value)
        {
            var article = new Article();

            article.Header      = value.Header;
            article.Summary     = value.Summary;
            article.Img         = value.Img;
            article.Body        = value.Body;
            article.Link        = value.Link;
            article.Source      = value.Source;
            article.Publishdate = value.Publishdate;
            articleService.AddArticle(article, value.Tags);
        }
예제 #14
0
        public ActionResult Add(ArticleVM viewModel, FormCollection form)
        {
            if (!ModelState.IsValid)
            {
                return(ShowValidateMessage());
            }
            var cats  = form["Category"].Split(',');
            var model = viewModel.MapTo <Article>();

            model.CreateTime = model.EditeTime = DateTime.Now;
            bll.AddArticle(model, form["Category"]);

            return(Json(new { Code = 1, Msg = "添加成功", RedirectUrl = "/AdminConsole/Article/Index" }));
        }
예제 #15
0
 public IActionResult AddAuthor([FromForm] AuthorViewModel authorViewModel)
 {
     if (ModelState.IsValid)
     {
         _authorService.AddAuthor(authorViewModel.Nickname,
                                  authorViewModel.Email,
                                  0);
         if (authorViewModel.ArticleContent != null)
         {
             _articleService.AddArticle(authorViewModel.Email, authorViewModel.ArticleTitle, authorViewModel.ArticleContent, DateTime.UtcNow);
         }
         return(Redirect(Url.Action("Index", "Home")));
     }
     return(View(authorViewModel));
 }
예제 #16
0
        public ActionResult CreateArticle(ArticleModel model)
        {
            if (ModelState.IsValid)
            {
                Article a       = _mapper.Map <Article>(model);
                Article article = _articleSrv.AddArticle(a);

                TempData["Msg"] = $"Artykuł dodany pomyślnie! Otrzymał ID = {article.Id}.";
                return(RedirectToAction("CreateArticle"));
            }
            else
            {
                // we must repopulate SelectList
                model.ArticleTypes = PrepareArticleTypes();
                return(View(model));
            }
        }
예제 #17
0
        public IActionResult Edit(ArticleViewModel article)
        {
            if (!ModelState.IsValid)
            {
                return(View("Edit", article));
            }

            if (article.Id != 0)
            {
                _articleService.SaveArticle(article);
            }
            else
            {
                _articleService.AddArticle(article);
            }
            return(RedirectToAction("Index"));
        }
예제 #18
0
        public async Task <IActionResult> Post([FromBody] Article article)
        {
            try
            {
                await _articleService.AddArticle(article);

                return(Ok());
            }
            catch (RecordAlreadyExistException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }
        }
        public IActionResult AddArticle(ArticleDto model)
        {
            if (string.IsNullOrEmpty(model.Content) || string.IsNullOrEmpty(model.Header))
            {
                return(Json(new { isNull = true, message = "Lütfen gerekli alanlarý doldurunuz." }));
            }

            var user = HttpContext.Session.GetObject <AuthorDto>("LoginUser");

            if (user == null || user.Id < 0)
            {
                return(Json(new { isNull = true, message = "Giriþ yapmadan yazý ekleyemezsiniz :(" }));
            }

            model.CreatedBy = user.Id;
            return(Ok(_articleService.AddArticle(model)));
        }
 public IActionResult AddArticle(TArticle article)
 {
     try
     {
         var result = ArticleService.AddArticle(article);
         if (result.Success)
         {
             return(Ok(result));
         }
         else
         {
             return(BadRequest(result.Message));
         }
     }
     catch (Exception ex)
     {
         logger.LogError(ex.Message);
         return(BadRequest(ex.Message));
     }
 }
예제 #21
0
        public async Task <IActionResult> AddArticle([FromBody] ArticleCreateModel articleCreateModel)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest());
                }

                var article = Mapper.Map <ArticleCreateModel, Article>(articleCreateModel);
                article.UserId = 1;
                article.Status = Status.Active;
                await _articleService.AddArticle(article);

                return(Ok(ModelFactory.CreateModel(article)));
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
예제 #22
0
        public async Task AddArticle_InsertDataToTable()
        {
            // Arrange
            Guid   id    = new Guid("16ef4cad-0bd1-4193-88f7-af3bf5b47dc0");
            string title = "title1";
            string body  = "body1";

            // Act
            await _articleService.AddArticle(id, title, body, DateTime.UtcNow);

            // Assert
            var article = await _dbMapper.QuerySingleOrDefaultAsync <ArticleInStorage>("select * from articles where id=@id",
                                                                                       new
            {
                id = id,
            });

            Assert.Equal(id, article.Id);
            Assert.Equal(title, article.Title);
            Assert.Equal(body, article.Body);
        }
예제 #23
0
        public async Task <HttpResponseMessage> AddArticle(Post article)
        {
            try
            {
                Request       = new HttpRequestMessage();
                configuration = new HttpConfiguration();
                Request.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration;

                var result = await _articleService.AddArticle(article);

                bool status = false;

                if (result)
                {
                    status = true;
                    return(Request.CreateResponse(HttpStatusCode.OK, status));
                }
                return(Request.CreateResponse(HttpStatusCode.OK, status));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to Post Article!"));
            }
        }
예제 #24
0
        static void AddArticles(IArticleService articleService)
        {
            Console.WriteLine("Adding articles ... ");

            Random random = new Random();

            // Add three articles
            for (int i = 1; i <= 3; i++)
            {
                var ean = "";
                for (int j = 0; j < 13; j++)
                {
                    ean += $"{random.Next(0,9)}";
                }

                articleService.AddArticle(new Article()
                {
                    EAN  = ean,
                    Name = $"Article{i}"
                });
            }

            Console.WriteLine("Articles added");
        }
 public async Task Handle(AddArticleContract contract)
 {
     await _articleService.AddArticle(Guid.NewGuid(), contract.Title, contract.Body, DateTime.UtcNow);
 }
        public async Task <IActionResult> Post([FromBody] RequestArticle article)
        {
            var responseModel = await _articleService.AddArticle(article);

            return(Created(string.Empty, $"{responseModel.Id}"));
        }
예제 #27
0
        public async Task <ActionResult <ArticleResource> > AddArticle([FromBody] AddArticleResource model, CancellationToken cancellationToken)
        {
            var userId = UserExtension.GetUserId(HttpContext);

            return(Ok(await _service.AddArticle(userId, model, cancellationToken)));
        }
        public ActionResult Create(ArticleModel model, HttpPostedFileBase datafile)
        {
            string command = Request.Form["submit"].ToString();

            switch (command)
            {
            case "Save":
            case "SaveAndContinueEdit":
                var alias        = Util.GetSEOAlias(model.Name);
                var checkArticle = _articleService.GetArticleByAlias(alias, model.CategoryId);
                if (checkArticle != null)
                {
                    ModelState.AddModelError("Name", "Alias đã được sử dụng");
                }
                if (ModelState.IsValid)
                {
                    if (model.CategoryId > 0)
                    {
                        var category = _categoryService.GetCategoryById(model.CategoryId);
                        if (category == null)
                        {
                            ErrorNotification("Danh mục không tồn tại.");
                            return(View(model));
                        }
                    }
                    var now = DateTime.Now;
                    if (datafile != null)
                    {
                        string[] fileExtensions = { ".jpg", ".jpeg", ".gif", ".png" };
                        string   extension      = Path.GetExtension(datafile.FileName).ToLower();
                        if (fileExtensions.Contains(extension))
                        {
                            string currentDir = _rootDir;
                            var    filePath   = _rootDir + datafile.FileName;
                            if (!Directory.Exists(Server.MapPath(currentDir)))
                            {
                                Directory.CreateDirectory(Server.MapPath(currentDir));
                            }
                            var path = Path.Combine(Server.MapPath(currentDir), Path.GetFileName(datafile.FileName));
                            datafile.SaveAs(path);
                            model.ImgPath = filePath;
                        }
                    }
                    if (model.Description == null)
                    {
                        model.Description = "";
                    }
                    try
                    {
                        var article = model.ToEntity();
                        article.CategoryId      = model.CategoryId;
                        article.Name            = model.Name;
                        article.CreatedOn       = now;
                        article.ModifiedOn      = now;
                        article.Content         = model.Content;
                        article.Status          = model.Status;
                        article.Description     = model.Description;
                        article.ImgPath         = model.ImgPath;
                        article.MetaTitle       = model.MetaTitle;
                        article.MetaDescription = model.MetaDescription;
                        article.Alias           = Util.GetSEOAlias(model.Name);
                        model.IsHighlight       = model.IsHighlight;
                        _articleService.AddArticle(article);

                        SuccessNotification("Thêm mới bài viết thành công!");
                        if (command == "SaveAndContinueEdit")
                        {
                            Title = "Thêm mới bài viết : " + article.Name;
                        }
                        else
                        {
                            return(RedirectToAction("Index"));
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorNotification(e.ToString());
                    }
                }
                else
                {
                    AddModelStateErrors();
                }
                break;

            default:
                ErrorNotification("Không rõ phương thức submit dữ liệu");
                return(RedirectToAction("Index"));
            }
            model.ListCategories = _categoryService.GetAllCategory().ToList();

            Title = "Thêm mới danh mục";
            ViewData["ToolbarTitle"] = Title;
            return(View(model));
        }
예제 #29
0
 public async Task <int> AddArticle(Article article)
 {
     return(await _articleService.AddArticle(article));
 }
예제 #30
0
 /// <summary>
 /// 添加梯调Article信息
 /// </summary>
 /// <param name="articleDto"></param>
 /// <returns></returns>
 public string AddArticle(ArticleDto articleDto)
 {
     _articleService.AddArticle(articleDto);
     return(JsonHelper.toLayuiMsg("ok"));
 }
예제 #31
0
 public ArticleModule(IArticleService service)
     : base("/article")
 {
     Get ["/tag"] = _ => {
         return "Tags";
     };
     Get ["/{slug}"] = _ => {
         string slug = _.slug;
         var article = service.Table.FirstOrDefault (ssss => ssss.Slug == slug);
         if (article != null) {
             string article_html = TemplatesCache.Current.Items["article_template"].Replace ("{article.content}", article.Content);
             article_html = article_html.Replace ("{article.title}", article.Title);
             article_html=article_html.Replace ("{article.href}","/article/"+article.Slug);
             article_html=TemplatesCache.Current.Items["index_template"].Replace ("{content}",article_html);
             article_html=article_html.Replace ("{strapdown}",TemplatesCache.Current.Items["strapdown_js"]);
             article_html=article_html.Replace ("{site.name}",TemplatesCache.Current.Items["site_name"]);
             article_html=article_html.Replace ("{copyright}",TemplatesCache.Current.Items["copy_right"]);
             return article_html;
         } else {
             return "Article Not Found !";
         }
     };
     Get ["/tag/{tag}"] = _ => {
         string tag = _.tag;
         return Response.AsJson (service.List (a => a.Tag.IndexOf (tag) > -1));
     };
     Get ["/"] = _ => {
         return Response.AsJson (service.Table.ToList ());
     };
     Post ["/"] = _ => {
         var article = this.Bind<Article> ();
         article.CreateTime=DateTime.Now;
         article.ID=DateTime.Now.ToString ("yyyyMMdd")+service.Table.Count ();
         service.AddArticle (article);
         return Response.AsJson (Message.Success);
     };
     Post ["/update"] = _ => {
         var article = this.Bind <Article>();
         service.UpdateArticle (article);
         return Response.AsJson (Message.Success);
     };
     Put ["/"] = _ => {
         var data = this.Bind <Article> ();
         service.UpdateArticle (data);
         return Response.AsJson (Message.Success);
     };
     Delete ["/id/{id}"] = _ => {
         string id=_.id;
         var article=service.GetSingleByID (id);
         service.DeleteArticle (article);
         return Response.AsJson (Message.Success);
     };
     Get ["/editor/{id}"] = _ => {
         string id=_.id;
         var article = service.GetSingleByID (id);
         string editor_template = TemplatesCache.Current.Items["editor_template"];
         editor_template=editor_template.Replace ("{post_url}","/article/update");
         editor_template=editor_template.Replace ("{title}",article.Title);
         editor_template=editor_template.Replace ("{slug}",article.Slug);
         editor_template=editor_template.Replace ("{tags}",article.Tag);
         editor_template=editor_template.Replace ("{content}",article.Content);
         return editor_template;
     };
     Get ["/editor"] = _ => {
         string editor_template = TemplatesCache.Current.Items["editor_template"];
         editor_template=editor_template.Replace ("{post_url}","/article/");
         editor_template=editor_template.Replace ("{title}","");
         editor_template=editor_template.Replace ("{slug}","");
         editor_template=editor_template.Replace ("{tags}","");
         editor_template=editor_template.Replace ("{content}","");
         return editor_template;
     };
 }