Exemplo n.º 1
0
        public ActionResult CreateArticle([FromBody] CreateArticleModel model)
        {
            if (!ApiUtils.IsModelValid(model))
            {
                return(BadRequest("模型无效"));
            }

            if (!LoginStatus.IsLoggedIn)
            {
                return(Unauthorized());
            }

            // 创建用户对象
            var article = new Article
            {
                Id         = Guid.NewGuid(),
                Title      = model.Title,
                Text       = model.Text,
                ThumbCount = 0,
                UserId     = LoginStatus.UserId             //
            };

            // 保存用户对象
            Context.Articles.Add(article);
            Context.SaveChanges();

            return(this.Ok(article.Id));
        }
Exemplo n.º 2
0
        public IActionResult Create(CreateArticleModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    string image = UploadImage(model);
                    if (model.Id == 0)
                    {
                        articles.Create(model.TopicId, model.Title, model.Text, model.Author, image);
                    }
                    else
                    {
                        // id is defined -> update
                        articles.Update(model.Id, model.TopicId, model.Title, model.Text, model.Author, image);
                    }

                    return(RedirectToAction(nameof(Index)));
                }
                catch (LogicException ex)
                {
                    ModelState.AddModelError("validation", ex.Message);
                }
            }

            model.Topics = topics.GetAllTopics();
            return(View(model));
        }
        public async Task <IActionResult> Create(CreateArticleModel articleModel)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(articleModel));
            }

            if (articleModel.Image.ContentType != "image/jpeg" &&
                articleModel.Image.ContentType != "image/png" &&
                articleModel.Image.ContentType != "svg+xml")
            {
                this.ModelState.AddModelError(string.Empty, InvalidImageType);

                return(this.View(articleModel));
            }

            articleModel.ImageUrl = await this.cloudinaryService.UploadAsync(articleModel.Image, articleModel.Image.FileName);

            var user = await this.userManager.GetUserAsync(this.User);

            if (user == null)
            {
                return(this.BadRequest());
            }

            articleModel.User = user;

            var serviceModel = AutoMapperConfig.MapperInstance.Map <CreateArticleServiceModel>(articleModel);

            await this.articlesService.CreateAsync(serviceModel);

            return(this.RedirectToAction("Index"));
        }
Exemplo n.º 4
0
        public ActionResult CreateArticle()
        {
            CreateArticleModel createArticle = new CreateArticleModel {
                AllTags = tagRepo.GetAllTags()
            };

            return(View(createArticle));
        }
Exemplo n.º 5
0
        public async Task CreateArticle(CreateArticleModel model)
        {
            var entity = _mapper.Map <ArticleEntity>(model);

            entity.DatePublished = DateTime.Now;

            _db.Article.Add(entity);
            await _db.SaveChangesAsync();
        }
Exemplo n.º 6
0
        public async Task <ArticleModel> Create(CreateArticleModel model)
        {
            var entityToSave = _conversor.MapTo <CreateArticleModel, Article>(model);

            _articlesDbContext.Articles.Add(entityToSave);
            await _articlesDbContext.SaveChangesAsync();

            return(_conversor.MapTo <Article, ArticleModel>(entityToSave));
        }
        public ActionResult Create(int id)
        {
            ViewBag.BlogId = id;
            CreateArticleModel cam = new CreateArticleModel()
            {
                BlogId = id
            };

            return(View(cam));
        }
Exemplo n.º 8
0
    public void CreateArticle(CreateArticleModel model, Action callback)
    {
        var request = new Request("articles/create", HTTPMethod.Post, model.GetJsonData().ToString(), model.ArticleImage);

        APIConnection.Conncetion.Request(request, (objects) =>
        {
            BBSDatas.Add(BBS.CreateData(objects.First()));
            callback();
        });
    }
Exemplo n.º 9
0
        public void Execute(CreateArticleModel model)
        {
            var date     = DateTime.UtcNow;
            var category = _repositories.GetCategory(model.CategoryId);

            var article = _factory.Create(date, category, model.Content);

            _unitOfWork.Save();

            _notifications.NotifyArticleOcurred(article.Id);
        }
Exemplo n.º 10
0
        public ActionResult Create(CreateArticleModel createArticleModel)
        {
            RequestContextData requestContextData = this.RequestContextData;

            IApplicationDataCache applicationDataCache = InstanceContainer.ApplicationDataCache;

            List <IWikiLanguageThreadLookupItem> wikiLanguageThreadLookupItems = applicationDataCache.GetWikiLanguageThreadIdLookup(requestContextData.ApplicationThemeInfo.ApplicationName);

            return(View(new CreateArticleModel(
                            5
                            , new SelectList(wikiLanguageThreadLookupItems, "ArticleGroupThreadId", "LanguageName")
                            )));
        }
        public ActionResult Create(CreateArticleModel model)
        {
            try
            {
                var article = Mapper.Map <CreateArticleModel, ArticleDTO>(model);
                artService.Create(article);

                return(RedirectToAction("ViewArticles", new { id = model.BlogId }));
            }
            catch
            {
                return(View());
            }
        }
        public ActionResult Create(CreateArticleModel model)
        {
            try
            {
                var article = Mapper.Map<CreateArticleModel, ArticleDTO>(model);
                artService.Create(article);

                return RedirectToAction("ViewArticles", new {id=model.BlogId });
            }
            catch
            {
                return View();
            }
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Create([FromBody] CreateArticleModel input)
        {
            var articleInfo = await _articleAppService.Create(new CreateArticleDto
            {
                CategoryId  = input.CategoryId,
                Content     = input.Content,
                CoverImgUrl = input.CoverImgUrl,
                IsTop       = input.IsTop,
                ShortDesc   = input.ShortDesc,
                Title       = input.Title,
                TagNum      = input.TagNum,
                TagStr      = input.TagStr,
                UserId      = AbpSession.UserId ?? 1
            });

            return(articleInfo != null?Json(true) : Json(false));
        }
        public Task <Option <ArticleModel, Error> > CreateAsync(string authorId, CreateArticleModel model) =>
        GetUserByIdOrError(authorId)
        .MapAsync(async author =>
        {
            var article = Mapper.Map <Article>(model);

            article.TagList   = FromTagListToDbCollection(article, model.TagList);
            article.AuthorId  = author.Id;
            article.CreatedAt = DateTime.UtcNow;
            article.UpdatedAt = DateTime.UtcNow;

            DbContext.Articles.Add(article);

            await DbContext.SaveChangesAsync();

            return(Mapper.Map <ArticleModel>(article));
        });
Exemplo n.º 15
0
        private string UploadImage(CreateArticleModel model)
        {
            string fileName = null;

            if (model.Image != null)
            {
                string uploadsFolder = Path.Combine(webHost.WebRootPath, "ArticleImages");
                //cfd9906f-a702-4ae7-b92f-94823bc0da3f_sample.png
                fileName = Guid.NewGuid().ToString() + "_" + model.Image.FileName;
                string fullFilePath = Path.Combine(uploadsFolder, fileName);

                using (var fileStream = new FileStream(fullFilePath, FileMode.Create))
                {
                    model.Image.CopyTo(fileStream);
                }
            }

            return(fileName);
        }
Exemplo n.º 16
0
        public ActionResult CreateArticle(CreateArticleModel a, string[] tags)
        {
            if (!ModelState.IsValid)
            {
                return(View(a));
            }
            if (tags == null || tags.Length == 0)
            {
                ModelState.AddModelError("tags", "Tag field required!");
                return(View(a));
            }
            Article newArticle = new Article
            {
                Title            = a.Title,
                ShortDescription = a.ShortDescription,
                FullDescription  = a.FullDescription,
                UserId           = User.Identity.GetUserId <int>()
            };

            if (a.Image != null)
            {
                newArticle.Image = a.Image.FileName;
            }
            else
            {
                newArticle.Image = "Empty";
            }
            newArticle.Tags.Clear();
            IEnumerable <Tag> articleTags = TagsHelper.CreateTagList(tags, tagRepo);

            TagsHelper.SetTagForModel(newArticle, articleTags);
            var id = repo.Save(newArticle);

            if (newArticle.Image != "Empty")
            {
                FileHelper fileHelper = new FileHelper();
                fileHelper.SaveOrUpdateArticleImage(Server.MapPath(ConfigurationManager.AppSettings["ArticlImagesFolder"]), a.Image, id);
            }
            return(RedirectToAction("Article", new { Id = id }));
        }
Exemplo n.º 17
0
        public ActionResult CreateArticle(CreateArticleModel article, string[] tags)
        {
            if (!ModelState.IsValid)
            {
                return(View(article));
            }
            tags = tags ?? new string[0];
            Article newArticle = new Article
            {
                Title            = article.Title,
                ShortDescription = article.ShortDescription,
                FullDescription  = article.FullDescription,
                UserId           = User.Identity.GetUserId <int>()
            };

            if (article.Image != null)
            {
                newArticle.Image = article.Image.FileName;
            }
            else
            {
                newArticle.Image = "Empty";
            }
            newArticle.Tags.Clear();
            IEnumerable <Tag> articleTags = TagsHelper.CreateTagList(tags, tagRepo);

            TagsHelper.SetTagForModel(newArticle, articleTags);
            var id = repo.Save(newArticle);

            if (newArticle.Image != "Empty")
            {
                FileHelper fileHelper = new FileHelper();
                fileHelper.SaveFIle(Server.MapPath(ConfigurationManager.AppSettings["ArticleImagesFolder"]), article.Image, id);
            }
            return(RedirectToAction("Article", new { Title = article.Title, Id = id }));
        }
Exemplo n.º 18
0
        public IActionResult Create(int?id)
        {
            if (!HttpContext.Session.GetIsAdmin())
            {
                return(NotFound());
            }

            var model = new CreateArticleModel();

            model.Author = HttpContext.Session.GetUsername();
            model.Topics = topics.GetAllTopics();

            if (id.HasValue)
            {
                var data = articles.GetById(id.Value);
                model.Author  = data.Author;
                model.Id      = data.Id;
                model.Text    = data.Text;
                model.Title   = data.Title;
                model.TopicId = data.TopicId;
            }

            return(View(model));
        }
Exemplo n.º 19
0
 protected override void OnPageShow()
 {
     _createArticleModel = new CreateArticleModel();
 }
 public async Task <IActionResult> Create([FromBody] CreateArticleModel data)
 {
     return(Json(data: await _articleService.CreateArticle(GetUserId(), data.CourseId, data.Article)));
 }
Exemplo n.º 21
0
        public async Task <ArticleModel> CreateArticle(CreateArticleModel model)
        {
            var result = await _writeArticleService.Create(model);

            return(result);
        }
 public ActionResult Create(int id)
 {
     ViewBag.BlogId = id;
     CreateArticleModel cam = new CreateArticleModel() { BlogId = id };
     return View(cam);
 }
Exemplo n.º 23
0
        public async Task <JsonResult> CreateArticle(CreateArticleModel model, List <HttpPostedFileBase> imagenes)
        {
            int     tipo            = 0;
            string  mensaje         = "";
            Boolean imagenesValidas = true;

            if (!ModelState.IsValid)
            {
                //Extrae el primer mensaje de error que tenga el modelo
                mensaje = ModelState.Values.Select(e => e.Errors).Where(e => e.Count > 0).FirstOrDefault().Select(v => v.ErrorMessage).FirstOrDefault();
            }

            if (mensaje == "")
            {
                if (imagenes == null)
                {
                    imagenes = new List <HttpPostedFileBase>();
                }

                if (imagenes.Count > 0)
                {
                    foreach (var im in imagenes)
                    {
                        if (im.ContentType.Split('/')[0] != "image")
                        {
                            imagenesValidas = false;
                        }
                    }

                    if (imagenesValidas)
                    {
                        try
                        {
                            using (var db = new VentaArticulosCreditoEntities())
                            {
                                var articulo = new Articulo(model.descripcion, model.subCategoria, model.nombre);
                                db.Articulo.Add(articulo);
                                db.SaveChanges();

                                foreach (var im in imagenes)
                                {
                                    var imagen = new Imagen_Articulo(articulo.codigo);

                                    db.Imagen_Articulo.Add(imagen);
                                    db.SaveChanges();
                                    imagen.imagen          = imagen.codigo + "." + im.ContentType.Split('/')[1];
                                    db.Entry(imagen).State = System.Data.Entity.EntityState.Modified;
                                    db.SaveChanges();
                                    im.SaveAs(ImagesPath() + imagen.imagen);
                                }

                                tipo    = 1;
                                mensaje = "Artículo creado correctamente";
                            }
                        }
                        catch (Exception ex)
                        {
                            mensaje = "Error al crear artículo";
                        }
                    }
                    else
                    {
                        mensaje = "Sólo se permiten imágenes";
                    }
                }
                else
                {
                    mensaje = "Seleccione al menos una imágen";
                }
            }

            return(Json(new { tipo = tipo, mensaje = mensaje }, JsonRequestBehavior.AllowGet));
        }
 public void SetModel(CreateArticleModel model)
 {
     _model              = model;
     _model.ImageLoaded += CreateContent;
     _model.LoadImages();
 }
Exemplo n.º 25
0
 public void SetParentArticleId(long id)
 {
     _createArticleModel          = new CreateArticleModel();
     _createArticleModel.ParentId = id;
 }