public ArticleViewModel PutArticle(ArticleViewModel item)
 {
     if (item.PictureUrl == null)
         item.PictureUrl = defaultPictureUrl;
     service.Update(item.ToBllArticle());
     return item;
 }
        public ActionResult Create(ArticleViewModel model, HttpPostedFileBase upload)
        {
            if (this.ModelState.IsValid)
            {
                var articleToAdd = new Article
                {
                    Title = model.Title,
                    Content = HttpUtility.HtmlDecode(model.Content),
                    CreatorId = this.User.Identity.GetUserId()
                };

                if (upload != null && upload.ContentLength > 0)
                {
                    var photo = new Data.Models.File
                    {
                        FileName = Path.GetFileName(upload.FileName),
                        FileType = FileType.Photo,
                        ContentType = upload.ContentType
                    };

                    using (var reader = new BinaryReader(upload.InputStream))
                    {
                        photo.Content = reader.ReadBytes(upload.ContentLength);
                    }

                    articleToAdd.Photo = photo;
                }

                this.articles.Add(articleToAdd);

                return this.RedirectToAction("Index");
            }

            return this.View(model);
        }
 public static ArticleViewModel Map(Article article)
 {
     ArticleViewModel viewModel = new ArticleViewModel();
     viewModel.Id = article.Id;
     viewModel.Title = article.Title;
     return viewModel;
 }
		public ArticleViewController (FeedItem feedItem)
		{
			this.feedItem = feedItem;
			ViewModel = new ArticleViewModel ();
			Title = "Статья";
			EdgesForExtendedLayout = UIRectEdge.None;
		}
 public ArticleViewModel PostArticle(ArticleViewModel item)
 {
     if (ModelState.IsValid)
     {
         if (item.PictureUrl == null)
             item.PictureUrl = defaultPictureUrl;
         service.Create(item.ToBllArticle());
         return item; 
     }
     return default(ArticleViewModel);
 }
        public ActionResult Article(int id)
        {
            var article = service.GetArticle(id);

            var avm = new ArticleViewModel()
            {
                Author = article.Author,
                Title = article.Title,
                Content = new HtmlString(article.Content),
                Tags = article.Tags?.Select(t => t.Title) ?? new List<string>(),
                HeaderImageSource = article.HeaderImageSource,
                OriginalSource = article.OriginalSource
            };
            return View(avm);
        }
        public ActionResult Add()
        {
            var urlReferrer = this.HttpContext.Request.UrlReferrer;
            var articleViewModel = new ArticleViewModel();

            if (urlReferrer != null)
            {
                articleViewModel.ReferrerUrl = urlReferrer.AbsoluteUri;
            }

            articleViewModel.CreatedOn = DateTime.Now;
            articleViewModel.Rubrics = this.GetRubricsAsCollectionOfListItems();
            articleViewModel.AuthorId = this.User.Identity.Name;

            return this.View(articleViewModel);
        }
Exemple #8
0
        public ActionResult Edit(ArticleViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (var db = new BlogDbContext())
                {
                    var article = db.Articles.FirstOrDefault(x => x.Id == model.Id);
                    article.Title   = model.Title;
                    article.Content = model.Content;

                    db.Entry(article).State = EntityState.Modified;
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            return(View());
        }
Exemple #9
0
        public void Test_ArticleController_ViewArticle()
        {
            // Arrange
            utils.CleanTables();
            Tuple <string, string> userIds = utils.CreateUsers();
            int article1 = utils.CreateSingleArticle(userIds.Item2);
            int article2 = utils.CreateSingleArticle(userIds.Item2);
            ArticleController controller = ControllerSetup(userIds.Item1, RoleType.Employee.ToString());

            // Act
            ArticleViewModel vm = controller.ViewArticle(article1).ViewData.Model as ArticleViewModel;

            // Assert
            Assert.IsNotNull(vm);
            Assert.AreEqual <int>(article1, vm.Id);
            Assert.AreEqual <string>(userIds.Item2, vm.AuthorId);
        }
Exemple #10
0
        public async Task <bool> UpdateArticleAsync(ArticleViewModel model)
        {
            try
            {
                var entity = _mapper.Map <Article>(model);
                _articleRepository.UpdateIgnore(entity, a => a.CreateTime);
                await _unitOfWork.SaveAsync();

                return(true);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                _logger.LogError(e.StackTrace);
                return(false);
            }
        }
Exemple #11
0
        public async Task <IActionResult> Create(ArticleViewModel articleViewModel)
        {
            if (ModelState.IsValid)
            {
                await _articleService.InsertAsync(articleViewModel);

                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                var errors = ModelState
                             .Where(x => x.Value.Errors.Count > 0)
                             .Select(x => new { x.Key, x.Value.Errors })
                             .ToArray();
            }
            return(RedirectToAction("Index", "Article", new { area = "Admin" }));
        }
Exemple #12
0
        public async Task <ArticleViewModel> GetArticleByIdAsync(int articleId)
        {
            ArticleViewModel articleViewModel = null;

            await Task.Run(() =>
            {
                var articleFromDb = this.context
                                    .Articles
                                    .Include(article => article.Author)
                                    .ThenInclude(author => author.Articles)
                                    .SingleOrDefault(article => article.Id == articleId);

                articleViewModel = this.mapper.Map <ArticleViewModel>(articleFromDb);
            });

            return(articleViewModel);
        }
Exemple #13
0
        public void Update(ArticleViewModel model)
        {
            var entity = new Articles();

            entity.ArticleId       = model.ArticleId;
            entity.ArticleDate     = model.ArticleDate;
            entity.AuthorName      = model.AuthorName;
            entity.Name            = model.Name;
            entity.Title           = model.Title;
            entity.Description     = model.Description;
            entity.Country         = model.Country;
            entity.ArticleMemberID = model.ArticleMemberId;

            entities.Articles.Attach(entity);
            entities.Entry(entity).State = EntityState.Modified;
            entities.SaveChanges();
        }
Exemple #14
0
        public void Create(ArticleViewModel model)
        {
            Articles entity = new Articles()
            {
                ArticleId       = model.ArticleId,
                ArticleDate     = model.ArticleDate,
                AuthorName      = model.AuthorName,
                Name            = model.Name,
                Title           = model.Title,
                Description     = model.Description,
                Country         = model.Country,
                ArticleMemberID = model.ArticleMemberId
            };

            entities.Articles.Add(entity);
            entities.SaveChanges();
        }
Exemple #15
0
        public ActionResult CreateArticle(ArticleViewModel model)
        {
            model.DatePublication = DateTime.Now;
            model.CountShows      = 0;
            model.CountLikes      = 0;
            if (model.SectionId == 0)
            {
                model.SectionId = 1;
            }
            model.BloggerId = Convert.ToInt32(HttpContext.Profile.GetPropertyValue("Id"));
            articleService.CreateArticle(model.ToBllArticle());
            var article = articleService.GetAllArticleEntities().Where(a => a.Title == model.Title && a.DatePublication == model.DatePublication).FirstOrDefault();

            TagHelper.CreateArticle(model.Tags, article.Id);

            return(RedirectToAction("ViewArticle", "Article", new { articleId = article.Id }));
        }
        public IActionResult AddArticle(ArticleViewModel model, IFormFile file)
        {
            int?sId = HttpContext.Session.GetInt32("ID");

            if (sId == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            //var fileName = Path.GetFileName(file.FileName);
            //var path = Path.Combine(Server.MapPath("~/Images"), fileName);
            //file.SaveAs(path);



            Articles article = new Articles();

            if (file != null && article != null)
            {
                var uniqueFileName = GetUniqueFileName(file.FileName);                       //benzersiz dosya ismi olusturuldu.
                var images         = Path.Combine(hostingEnvironment.WebRootPath, "Images"); //wwwroot klasorune kadarki yol alınıp images ile birleştirildi
                var filePath       = Path.Combine(images, uniqueFileName);                   //dosya yolu ve adı birşetirildi.
                file.CopyTo(new FileStream(filePath, FileMode.Create));

                article.Title         = model.article.Title;
                article.Text          = model.article.Text;
                article.CategoryID    = model.article.CategoryID;
                article.DefaultImage  = uniqueFileName;
                article.UserID        = sId;
                article.AddDate       = DateTime.Now;
                article.ArticleStatus = true;
                db.Articles.Add(article);
                db.SaveChanges();
                return(RedirectToAction("UserArticle", "Article"));
            }
            else
            {
                ViewBag.Warning = "Article is not added.";
                ViewBag.Status  = "danger";
            }
            var list = db.Categories.ToList();

            model.categoriSelectList = new SelectList(list, "ID", "CategoriName");

            return(View(model));
        }
        private ArticleViewModel GetFullArticle(long id)
        {
            var article = ArticleService.Get(id);

            if (article == null)
            {
                return(null);
            }

            var isLoggedIn = false;

            User user = null;

            if (User.Identity.Name != null)
            {
                user = UserService.Get(long.Parse(User.Identity.Name));

                if (user != null)
                {
                    isLoggedIn = true;
                }
            }

            var likes = ArticleLikeService.GetAll()
                        .Where(x => x.Article == article)
                        .ToList();

            var comments = ArticleCommentService.GetArticleComments(article);

            var isLiked = false;

            if (isLoggedIn)
            {
                if (likes.FirstOrDefault(x => x.Author == user) != null)
                {
                    isLiked = true;
                }
            }

            var result = new ArticleViewModel(article, likes, comments, isLiked);

            result.Author.Rating = ReviewService.GetSpecialistRating(article.Author);

            return(result);
        }
Exemple #18
0
        public ActionResult Create(ArticleViewModel model)
        {
            // insert article in DB
            if (ModelState.IsValid)
            {
                using (var database = new BlogDbContext())
                {
                    // Get author id
                    var authorId = database.Users
                                   .Where(u => u.UserName == this.User.Identity.Name)
                                   .First()
                                   .Id;

                    var article = new Article(authorId, model.Title, model.Content, model.CategoryId);

                    // Check if model.Tags is empty or null start added by Le0ne
                    if (model.Tags == null)
                    {
                        return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                    }

                    var modeltags = model.Tags
                                    .Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
                                    .Select(t => t.ToLower())
                                    .Distinct()
                                    .ToList();

                    if (modeltags.Count == 0)
                    {
                        return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                    }
                    // end added by Le0ne

                    this.SetArticleTags(article, model, database);

                    // Save article in DB
                    database.Articles.Add(article);
                    database.SaveChanges();

                    return(RedirectToAction("Index"));
                }
            }

            return(View(model));
        }
        public async Task <IActionResult> Create(ArticleViewModel article, IFormFile Image)
        {
            if (string.IsNullOrEmpty(article.Title))
            {
                article.Exception.Message = "სათაური აუცილებელია!";

                return(View(article));
            }

            if (string.IsNullOrEmpty(article.Phone) || (!string.IsNullOrEmpty(article.Phone) && article.Phone.Any(x => !char.IsDigit(x))))
            {
                article.Exception.Message = "ტელეფონის ნომერი აუცილებელია და უნდა შეიცავდეს მხოლოდ ციფრებს";

                return(View(article));
            }
            if (Image != null)
            {
                using (var stream = new MemoryStream())
                {
                    await Image.CopyToAsync(stream);

                    article.Image = stream.ToArray();

                    try
                    {
                        var result = _mapper.Map <ArticleViewModel, Article>(article);

                        await apiClient.Articles.Add(result);

                        return(RedirectToAction("Index"));
                    }
                    catch
                    {
                        article.Exception.Message = "განცხადების ატვირთვისას მოხდა შეცდომა, გთხოვთ სცადოთ მოგვიანებით";

                        return(View(article));
                    }
                }
            }


            article.Exception.Message = "სურათი აუცილებელია!";

            return(View(article));
        }
Exemple #20
0
        //[ValidateAntiForgeryToken]
        public ActionResult Create(ArticleViewModel model)
        {
            using (var db = new BlogDbContext())
            {
                var user = db.Users.FirstOrDefault(u => u.UserName.Equals(this.User.Identity.Name));

                var article = new Article(user.Id, model.Title, model.Content, model.CategoryId);
                //article.AuthorId = user.Id;
                //article.Title = model.Title;
                //article.Content = model.Content;
                //article.CategoryId = model.CategoryId;

                this.SetArticleTags(article, model, db);

                db.Articles.Add(article);
                db.SaveChanges();
                //if (file != null)
                //{
                //        var image = new ArticleImage();

                //        string pic = System.IO.Path.GetFileName(file.FileName);
                //    pic = "new" + pic;
                //    string path = System.IO.Path.Combine(
                //                           Server.MapPath("~/images"), pic);
                //    // file is uploaded
                //    file.SaveAs(path);
                //        image.ArticleId = article.Id;
                //        image.FileName = file.FileName;


                //    // save the image path path to the database or you can send image
                //    // directly to database
                //    // in-case if you want to store byte[] ie. for DB
                //    using (MemoryStream ms = new MemoryStream())
                //    {
                //        file.InputStream.CopyTo(ms);
                //        byte[] array = ms.GetBuffer();
                //    }


                //}
                //// after successfully uploading redirect the user
                return(RedirectToAction("ListUserArticles", new { user.Id }));
            }
        }
Exemple #21
0
        public ActionResult PropertiesPost(string tabId, int parentId, int id, string backendActionCode, bool?boundToExternal)
        {
            var data  = ArticleService.ReadForUpdate(id, parentId);
            var model = ArticleViewModel.Create(data, tabId, parentId, boundToExternal);

            // ReSharper disable once PossibleInvalidOperationException
            PersistFromId(model.Data.Id, model.Data.UniqueId.Value);

            TryUpdateModel(model);
            model.Validate(ModelState);
            if (ModelState.IsValid)
            {
                try
                {
                    model.Data = ArticleService.Update(model.Data, backendActionCode, boundToExternal, HttpContext.IsXmlDbUpdateReplayAction());

                    // ReSharper disable once PossibleInvalidOperationException
                    PersistResultId(model.Data.Id, model.Data.UniqueId.Value);
                    var union = model.Data.AggregatedArticles.Any()
                        ? model.Data.FieldValues.Union(model.Data.AggregatedArticles.SelectMany(f => f.FieldValues))
                        : model.Data.FieldValues;

                    foreach (var fv in union.Where(f => new[] { FieldExactTypes.O2MRelation, FieldExactTypes.M2MRelation, FieldExactTypes.M2ORelation }.Contains(f.Field.ExactType)))
                    {
                        AppendFormGuidsFromIds($"field_{fv.Field.Id}", $"field_uniqueid_{fv.Field.Id}");
                    }

                    return(Redirect("Properties", new
                    {
                        tabId,
                        parentId,
                        id = model.Data.Id,
                        successfulActionCode = backendActionCode,
                        boundToExternal
                    }));
                }
                catch (ActionNotAllowedException nae)
                {
                    ModelState.AddModelError("OperationIsNotAllowedForAggregated", nae.Message);
                    return(JsonHtml("Properties", model));
                }
            }

            return(JsonHtml("Properties", model));
        }
Exemple #22
0
        public async Task <IActionResult> PutArticle([FromBody] ArticleViewModel articleVm)
        {
            var dr = await _articleRepository.GetArticlesByCatSect(articleVm.articleCategoryID, articleVm.SectionID);

            if (!ModelState.IsValid)
            {
                throw new Exception(string.Join("\n", ModelState.Keys.SelectMany(k => ModelState[k].Errors).Select(m => m.ErrorMessage).ToArray()));
            }
            else if (dr != null)
            {
                if (dr.Count() > 7)
                {
                    throw new Exception("There is too many articles in this section already Delete some");
                }
                {
                    var artic = new Article();

                    var _article = await _articleRepository.GetArticle(articleVm.ID);

                    if (_article == null)
                    {
                        throw new Exception("Invalid article.");
                    }
                    else
                    {
                        try
                        {
                            artic.UpdateToArticle(articleVm);
                            //_article.UpdateToArticle(articleVm);

                            await _articleRepository.UpdateArticle(artic);


                            return(Ok());
                        }

                        catch (AppException ex)
                        {
                            return(BadRequest(new { message = ex.Message }));
                        }
                    }
                }
            }
            return(Ok());
        }
Exemple #23
0
        public Article CreateArticleFromViewModel(ArticleViewModel articleViewModel, string userId)
        {
            var article = new Article
            {
                CategoryId       = articleViewModel.Category.Id,
                IsDraft          = articleViewModel.IsDraft ? 1 : 0,
                PublishEndDate   = articleViewModel.PublishEndDate,
                PublishStartDate = articleViewModel.PublishStartDate,
                Created          = DateTime.Now,
                Edited           = DateTime.Now,
                Title            = articleViewModel.Title,
                Content          = articleViewModel.Content,
                SefName          = articleViewModel.SefName,
                AuthorId         = userId.ToString()
            };

            return(article);
        }
Exemple #24
0
 public ActionResult CreateArticle(ArticleViewModel articleModel, string tagList)
 {
     if (ModelState.IsValid)
     {
         articleModel.UserProfileId = AuthenticationManager.User.Identity.GetUserId();
         articleModel.Date          = DateTime.Now;
         if (!tagList.IsNullOrWhiteSpace())
         {
             articleModel.Tags = new List <string>(tagList.Split(' '));
         }
         _articleService.Create(_mapper.Map <ArticleDTO>(articleModel));
         return(RedirectToAction("Index"));
     }
     else
     {
         return(View(articleModel));
     }
 }
Exemple #25
0
        public ArticlePage()
        {
            InitializeComponent();
            _articleViewModel = DataContext as ArticleViewModel;

            if (App.Current.Resources.Contains("settings"))
            {
                settings = App.Current.Resources["settings"] as SettingsClass;
                if (settings == null)
                {
                    settings = new SettingsClass();
                }
            }
            else
            {
                settings = new SettingsClass();
            }
        }
        public ActionResult Edit(ArticleViewModel vm)
        {
            if (ModelState.IsValid)
            {
                vm.Article.ArticleHeadline = _uow.MultiLangStrings.GetById(vm.Article.ArticleHeadlineId);
                vm.Article.ArticleHeadline.SetTranslation(vm.ArticleHeadline, CultureHelper.GetCurrentNeutralUICulture(),
                                                          nameof(vm.Article) + "." + vm.Article.ArticleId + "." + nameof(vm.Article.ArticleHeadline));

                vm.Article.ArticleBody = _uow.MultiLangStrings.GetById(vm.Article.ArticleBodyId);
                vm.Article.ArticleBody.SetTranslation(vm.ArticleBody, CultureHelper.GetCurrentNeutralUICulture(),
                                                      nameof(vm.Article) + "." + vm.Article.ArticleId + "." + nameof(vm.Article.ArticleBody));

                _uow.Articles.Update(vm.Article);
                _uow.Commit();
                return(RedirectToAction(nameof(Index)));
            }
            return(View(vm));
        }
Exemple #27
0
        public async Task Insert_ShouldAddedNewArticle()
        {
            // arrange
            var article = new ArticleViewModel {
                Name = Guid.NewGuid().ToString()
            };

            var client = _factory.CreateClient();

            // act
            var response = await client.PostAsync(ArticlesUrl, GetContent(article)).ConfigureAwait(false);

            // assert
            response.StatusCode.ShouldBe(HttpStatusCode.OK);
            var result = await GetResult <Guid>(response).ConfigureAwait(false);

            result.ShouldNotBeNull();
        }
Exemple #28
0
        public ActionResult Create(ArticleViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            model.LangId = Lang.Rus;

            var articleBL = _mapper.Map <ArticleBL>(model);

            articleBL.AuthorId = User.Identity.GetUserId();
            articleBL.Date     = DateTime.Now;

            _articleService.Create(articleBL);

            return(RedirectToAction("Index"));
        }
        public ActionResult Create(ArticleViewModel vm)
        {
            if (ModelState.IsValid)
            {
                vm.Article.ArticleHeadline = new MultiLangString(vm.ArticleHeadline,
                                                                 CultureHelper.GetCurrentNeutralUICulture(), vm.ArticleHeadline,
                                                                 nameof(vm.Article) + "." + vm.Article.ArticleId + "." + nameof(vm.Article.ArticleHeadline));
                vm.Article.ArticleBody = new MultiLangString(vm.ArticleBody, CultureHelper.GetCurrentNeutralUICulture(),
                                                             vm.ArticleBody,
                                                             nameof(vm.Article) + "." + vm.Article.ArticleId + "." + nameof(vm.Article.ArticleBody));

                _uow.Articles.Add(vm.Article);
                _uow.Commit();
                return(RedirectToAction(nameof(Index)));
            }

            return(View(vm));
        }
        public Article CreateArticleFromViewModel(ArticleViewModel articleViewModel, long userId)
        {
            var article = new Article
            {
                CategoryId       = articleViewModel.Category.Id,
                IsDraft          = articleViewModel.IsDraft ? 1 : 0,
                PublishEndDate   = articleViewModel.PublishEndDate,
                PublishStartDate = articleViewModel.PublishStartDate,
                Created          = DateTime.Now,
                Edited           = DateTime.Now,
                Title            = articleViewModel.Title,
                Content          = articleViewModel.Content,
                Author           = userId,
                LastAuthorEdited = userId
            };

            return(article);
        }
Exemple #31
0
        public ActionResult Create()
        {
            //check if we have error messages from our last attempt to create a post
            if (TempData["message"] != null)
            {
                ViewBag.Message = TempData["message"].ToString();
            }


            using (var databse = new BlogDBContext())
            {
                var model = new ArticleViewModel();
                model.Categories = databse.Categories
                                   .OrderBy(c => c.Name)
                                   .ToList();
                return(View(model));
            }
        }
Exemple #32
0
        public async Task <bool> AddArticleAsync(ArticleViewModel model)
        {
            try
            {
                var article = _mapper.Map <Article>(model);
                await _articleRepository.AddAsync(article);

                await _unitOfWork.SaveAsync();

                return(true);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                _logger.LogError(e.StackTrace);
                return(false);
            }
        }
Exemple #33
0
        private async Task <BaseModel> Save(ArticleViewModel model, UsersLoginDataModel user, CommunityGroupsDataModel communityGroupsData)
        {
            CommunityArticles dataModel = new CommunityArticles
            {
                CreatedBy       = model.UserId,
                User            = user,
                CommunityGroups = communityGroupsData,
                Title           = model.ArticleTitle,
                Description     = model.ArticleDescription,
                ShareDocUrl     = model.ShareDocument,
                IsActive        = true,
            };
            await _unitOfWork.UserCommunityArticlesRepository.Insert(dataModel);

            return(new BaseModel {
                Status = true, Id = dataModel.Id, Messsage = UMessagesInfo.RecordSaved
            });
        }
Exemple #34
0
        public ActionResult Edit(ArticleViewModel article)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(apiBaseAddress);

                //HTTP POST
                var putTask = client.PutAsJsonAsync <ArticleViewModel>("Article/UpdatePost", article);
                putTask.Wait();

                var result = putTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    return(RedirectToAction("Index"));
                }
            }
            return(View(article));
        }
Exemple #35
0
        public ActionResult ArticleDetail(int articleid)
        {
            ArticleViewModel vm = new ArticleViewModel();

            Articles article = db.Articles.Where(c => c.ArticleIDX == articleid).FirstOrDefault();

            article.ViewCnt += 1;
            db.SaveChanges();


            article = db.Articles.Where(c => c.ArticleIDX == articleid).FirstOrDefault();
            List <ArticleFiles> files = db.ArticleFiles.Where(c => c.ArticleIDX == articleid).OrderBy(o => o.UploadDate).ToList();

            vm.Article = article;
            vm.Files   = files;

            return(View(vm));
        }
Exemple #36
0
        public ActionResult Edit(ArticleViewModel model)
        {
            if (ModelState.IsValid)
            {
                var database = new BlogDbContext();

                var articles = database.Articles.FirstOrDefault(a => a.Id == model.Id);

                articles.Title   = model.Title;
                articles.Content = model.Content;

                database.Entry(articles).State = EntityState.Modified;
                database.SaveChanges();

                return(RedirectToAction("Index"));
            }
            return(View(model));
        }
        public ActionResult EditArticle(ArticleViewModel article)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:50988/api/article/EditArticle");

                //HTTP POST
                var putTask = client.PutAsJsonAsync <ArticleViewModel>("EditArticle", article);
                putTask.Wait();

                var result = putTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    return(RedirectToAction("Index"));
                }
            }
            return(View(article));
        }
Exemple #38
0
        public ActionResult Create(ArticleViewModel model)
        {
            ViewBag.Data_ArticleCode = GetForeignData();
            ServiceResult result = new ServiceResult();
            TempData["Service_Result"] = result;
            if (ModelState.IsValid)
            {
                try
                {
                    Article article = new Article()
                    {
                        AddTime = DateTime.Now,
                        ArticleCodeValue = model.ArticleCode,
                        Content = model.Content,
                        Name = model.Name,
                        LastTime = DateTime.Now,
                        ArticleCode = Convert.ToInt32(model.ArticleCode.Split(',').Last())
                    };

                    ArticleService.Create(article);
                    result.Message = "添加文章信息成功!";
                    LogHelper.WriteLog("添加文章信息成功");
                    return RedirectToAction("index");
                }
                catch (Exception ex)
                {
                    result.Message = Utilities.GetInnerMostException(ex);
                    result.AddServiceError(result.Message);
                    LogHelper.WriteLog("添加文章信息错误", ex);
                    return View(model);
                }
            }
            else
            {
                result.Message = "请检查表单是否填写完整!";
                result.AddServiceError("请检查表单是否填写完整!");
                return View(model);
            }
        }
        public ActionResult Add(ArticleViewModel model)
        {
            if (this.articleService.AnyByTitle(model.Title))
            {
                this.ModelState.AddModelError("Title", ModelConstants.TitleExist);

                var currentImage = this.imageService.GetById(model.ImageId ?? 0);

                if (currentImage != null)
                {
                    this.ViewBag.ImagePath = currentImage.ImagePath;
                    this.ViewBag.ImageDesc = currentImage.ImageDescription;
                }

                model.Rubrics = this.GetRubricsAsCollectionOfListItems(model.RubricId);
                return this.View(model);
            }

            if (this.ModelState.IsValid)
            {
                Article article = this.MakeArtilceFromModel(model);
                article.Tags = this.GetTags(model.Tags);

                this.articleService.Add(article);

                if (model.ReferrerUrl != null)
                {
                    return this.Redirect(model.ReferrerUrl);
                }

                return this.RedirectToAction("Index");
            }

            model.Rubrics = this.GetRubricsAsCollectionOfListItems(model.RubricId);

            return this.View(model);
        }
 /// <summary>
 /// Validates the article model.
 /// </summary>
 /// <param name="model">The model.</param>
 /// <param name="modelState">State of the model.</param>
 public static void ValidateArticle(ArticleViewModel model, ModelStateDictionary modelState)
 {
     if (!String.IsNullOrEmpty(model.Url))
     {
         if (model.UrlType == ArticleUrlType.External)
         {
             if (!Regex.IsMatch(model.Url, RegexValidationConfig.GetPattern(RegexTemplates.Url)))
             {
                 modelState.AddModelError(PropertyName.For<ArticleViewModel>(item => item.Url),
                 ResourceHelper.TranslateErrorMessage(new HttpContextWrapper(HttpContext.Current), typeof(ArticleViewModel),
                 PropertyName.For<ArticleViewModel>(item => item.Url), "regularexpression", null));
             }
         }
         else if (model.UrlType == ArticleUrlType.Internal)
         {
             if (!Regex.IsMatch(model.Url, RegexValidationConfig.GetPattern(RegexTemplates.UrlPart)))
             {
                 modelState.AddModelError(PropertyName.For<ArticleViewModel>(item => item.Url),
                 ResourceHelper.TranslateErrorMessage(new HttpContextWrapper(HttpContext.Current), typeof(ArticleViewModel),
                 PropertyName.For<ArticleViewModel>(item => item.Url), "regularexpression", null));
             }
         }
     }
 }
Exemple #41
0
        public ArticleViewModel GetArticleById(int id)
        {
            ArticleViewModel model = new ArticleViewModel();
            if (this.ArticleExists(id))
            {
                Article dbArticle = this.Data.Articles.Find(id);
                model = this.MapArticleViewModel(dbArticle);
            }
            else
            {
                model.Content = "Не съществува такава статия!";
                model.Title = "НЕСЪЩЕСТВУВАЩА АТКРАКЦИЯ!";
            }

            return model;
        }
Exemple #42
0
 public ActionResult Edit(ArticleViewModel model)
 {
     List<int> ids = model.ArticleCode.Split(',').Select(x => Convert.ToInt32(x)).ToList();
     ViewBag.Data_ArticleCode = GetForeignData(ids);
     ServiceResult result = new ServiceResult();
     TempData["Service_Result"] = result;
     if (ModelState.IsValid)
     {
         try
         {
             Article entity = new Article()
             {
                 ID = model.ID,
                 Name = model.Name,
                 Content = model.Content,
                 ArticleCodeValue = model.ArticleCode,
                 ArticleCode = Convert.ToInt32(model.ArticleCode.Split(',').Last()),
                 LastTime = DateTime.Now
             };
             ArticleService.Update(entity);
             result.Message = "编辑文章信息成功!";
             LogHelper.WriteLog("编辑文章信息成功");
             return RedirectToAction("index");
         }
         catch (Exception ex)
         {
             result.Message = Utilities.GetInnerMostException(ex);
             result.AddServiceError(result.Message);
             LogHelper.WriteLog("编辑文章信息错误", ex);
             return View(model);
         }
     }
     else
     {
         result.Message = "请检查表单是否填写完整!";
         result.AddServiceError("请检查表单是否填写完整!");
         return View(model);
     }
 }
        public virtual ActionResult New(ArticleViewModel article)
        {
            ArticleHelper.ValidateArticle(article, ModelState);
            if (ModelState.IsValid)
            {
                var newArticle = article.MapTo(new Article
                                                   {
                                                       UserId = this.CorePrincipal() != null ? this.CorePrincipal().PrincipalId : (long?)null,
                                                       CreateDate = DateTime.Now
                                                   });
                if (articleService.Save(newArticle))
                {
                    permissionService.SetupDefaultRolePermissions(OperationsHelper.GetOperations<ArticleOperations>(), typeof(Article), newArticle.Id);
                    Success(HttpContext.Translate("Messages.Success", String.Empty));
                    return RedirectToAction(WebContentMVC.Article.Show());
                }
            }
            else
            {
                Error(HttpContext.Translate("Messages.ValidationError", String.Empty));

            }

            article.AllowManage = true;
            return View("New", article);
        }
Exemple #44
0
 public ActionResult Edit(int id)
 {
     Article article = ArticleService.Find(id);
     List<int> ids = article.ArticleCodeValue.Split(',').Select(x => Convert.ToInt32(x)).ToList();
     ViewBag.Data_ArticleCode = GetForeignData(ids);
     ArticleViewModel model = new ArticleViewModel()
     {
         Name = article.Name,
         ID = article.ID,
         ArticleCode = article.ArticleCodeValue,
         Content = article.Content
     };
     return View(model);
 }
 public ArticleView(ArticleViewModel viewModel)
 {
     InitializeComponent();
     this.DataContext = viewModel;
 }
Exemple #46
0
        private ArticleViewModel MapArticleViewModel(Article dbArticle)
        {
            ArticleViewModel model = new ArticleViewModel();
            model.Id = dbArticle.Id;
            model.Title = dbArticle.Title;
            model.Image = dbArticle.Image;
            model.DateAdded = dbArticle.DateAdded;
            model.Summary = dbArticle.Summary;
            model.Content = dbArticle.Content;

            return model;
        }
        private Article MakeArtilceFromModel(ArticleViewModel model)
        {
            var article = new Article
            {
                Title = model.Title,
                Description = model.Description,
                Content = model.Content,
                IsPublished = model.IsPublished,
                CreatedOn = model.CreatedOn,
                PublishDate = DateTime.Parse(model.PublishDate.ToString()),
                UnpublishDate = model.UnpublishDate,
                ImageId = model.ImageId,
                Alias = model.Alias,
                RubricId = model.RubricId,
                AuthorId = this.User.Identity.GetUserId(),
                Tags = model.Tags == null ? null : this.GetTags(model.Tags),
            };

            return article;
        }
        public ActionResult Update(ArticleViewModel model)
        {
            if (this.articleService.AnyByTitleAndId(model.Title, model.Id))
            {
                this.ModelState.AddModelError("Title", "Заглавието вече съществува");
            }

            if (!this.ModelState.IsValid)
            {
                return this.RedirectToAction("Update", "Article", model);
            }

            var articleFromDb = this.articleService.GetById(model.Id);

            articleFromDb.Tags.Clear();
            this.articleService.Update(articleFromDb);

            articleFromDb.Tags = this.GetTags(model.Tags);
            articleFromDb.Title = model.Title;
            articleFromDb.Description = model.Description;
            articleFromDb.Content = model.Content;
            articleFromDb.IsPublished = model.IsPublished;
            articleFromDb.PublishDate = DateTime.Parse(model.PublishDate.ToString());
            articleFromDb.UnpublishDate = model.UnpublishDate;
            articleFromDb.ImageId = model.ImageId;
            articleFromDb.Alias = model.Alias;
            articleFromDb.RubricId = model.RubricId;
            articleFromDb.AuthorId = this.User.Identity.GetUserId();

            this.articleService.Update(articleFromDb);

            if (model.ReferrerUrl != null)
            {
                return this.Redirect(model.ReferrerUrl);
            }

            return this.RedirectToAction("Index", "Article");
        }
        public virtual ActionResult Save(ArticleViewModel model)
        {
            ArticleHelper.ValidateArticle(model, ModelState);
            if (ModelState.IsValid)
            {
                var article = articleService.Find(model.Id);

                if (article == null || !permissionService.IsAllowed((Int32)ArticleOperations.Manage, this.CorePrincipal(), typeof(Article), article.Id, IsArticleOwner(article), PermissionOperationLevel.Object))
                {
                    throw new HttpException((int)HttpStatusCode.NotFound, HttpContext.Translate("Messages.NotFound", ResourceHelper.GetControllerScope(this)));
                }

                if (articleService.Save(model.MapTo(article)))
                {
                    //save locale
                    var localeService = ServiceLocator.Current.GetInstance<IArticleLocaleService>();
                    ArticleLocale locale = localeService.GetLocale(article.Id, model.SelectedCulture);
                    locale = model.MapLocaleTo(locale ?? new ArticleLocale { Article = article });

                    localeService.Save(locale);

                    Success(HttpContext.Translate("Messages.Success", String.Empty));
                    return RedirectToAction(WebContentMVC.Article.Edit(model.Id));
                }
            }
            else
            {
                Error(HttpContext.Translate("Messages.ValidationError", String.Empty));
            }

            model.AllowManage = true;

            return View("Edit", model);
        }
        public virtual ActionResult ShowFiles(long articleId)
        {
            var article = articleService.Find(articleId);

            if (article == null || !permissionService.IsAllowed((Int32)ArticleOperations.View, this.CorePrincipal(), typeof(Article), article.Id, IsArticleOwner(article), PermissionOperationLevel.Object))
            {
                throw new HttpException((int)HttpStatusCode.NotFound, HttpContext.Translate("Messages.NotFound", ResourceHelper.GetControllerScope(this)));
            }

            IList<GridColumnViewModel> columns = new List<GridColumnViewModel>
                                                     {
                                                         new GridColumnViewModel
                                                             {
                                                                 Name = HttpContext.Translate("Title", ResourceHelper.GetControllerScope(this)), 
                                                                 Sortable = false,
                                                             },
                                                         new GridColumnViewModel
                                                             {
                                                                 Width = 10,
                                                                 Sortable = false
                                                             },
                                                         new GridColumnViewModel
                                                             {
                                                                 Name = "Id", 
                                                                 Sortable = false, 
                                                                 Hidden = true
                                                             }
                                                     };
            var model = new GridViewModel
            {
                DataUrl = Url.Action("LoadFilesData", "Article", new { articleId = article.Id }),
                DefaultOrderColumn = "Title",
                GridTitle = HttpContext.Translate("Titles.ArticleFiles", ResourceHelper.GetControllerScope(this)),
                Columns = columns,
                IsRowNotClickable = true
            };

            bool allowManage = permissionService.IsAllowed((Int32)ArticleOperations.Manage, this.CorePrincipal(),
                                                            typeof(Article), article.Id, IsArticleOwner(article),
                                                            PermissionOperationLevel.Object);

            ViewData["Article"] = new ArticleViewModel { Id = article.Id, AllowManage = allowManage };

            return View("ArticleFiles", model);
        }
 public ArticleController()
 {
     this._article = new ArticleViewModel
     {
         Article =
             new Article
             {
                 ArticleId = 1, PublicationDate = new DateTime(2015, 2, 22, 17, 24, 45),
                 Title = "Делаем приватный монитор из старого LCD монитора",
                 Text =
                     @"<br>Вы наконец-то можете сделать кое-что со своим старым LCD монитором, который завалялся у Вас в гараже. Превратите его в шпионский монитор! Для всех вокруг он будет выглядеть просто белым экраном, но не для Вас, потому что у Вас будут специальные «волшебные» очки.<br><br>Всё что Вам нужно – это пара старых очков, нож для бумаги и растворитель для краски.<br><br>",
                 Topic = new Topic { TopicId = 2, Name = "DIY или Сделай Сам" },
                 Tags =
                 {
                     new Tag { TagId = 3, Name = "tag one" }, new Tag { TagId = 4, Name = "tag two" },
                     new Tag { TagId = 5, Name = "tag three" }, new Tag { TagId = 6, Name = "tag four" }
                 },
                 User = new User { UserId = 7, FirstName = "John", LastName = "Grey" }
             },
         ViewsCount = 137,
         CommentsCount = 6, FavsCount = 12,
         VotingInfo = new VotingInfo { PositiveVotesCount = 1234, NegativeVotesCount = 234 },
         Comments =
             new[]
             {
                 new CommentViewModel
                 {
                     Comment =
                         new Comment
                         {
                             CommentId = 8, Date = new DateTime(2015, 2, 22, 17, 24, 45),
                             Text = "Some comment text.<br> Comment line.",
                             CommentEdit = new CommentEdit { EditDate = new DateTime(2015, 2, 22, 17, 26, 07) },
                             User = new User { UserId = 7, FirstName = "John", LastName = "Grey" }
                         },
                     VotingInfo = new VotingInfo { PositiveVotesCount = 1234, NegativeVotesCount = 234 },
                     IsFromArticleAuthor = true
                 },
                 new CommentViewModel
                 {
                     Comment =
                         new Comment
                         {
                             CommentId = 9, Date = new DateTime(2015, 2, 22, 17, 24, 45),
                             Text = "Some comment text.<br> Comment line.",
                             User = new User { UserId = 7, FirstName = "John", LastName = "Grey" }
                         },
                     Replies =
                         new[]
                         {
                             new CommentViewModel
                             {
                                 Comment =
                                     new Comment
                                     {
                                         CommentId = 10, Date = new DateTime(2015, 2, 22, 17, 24, 45),
                                         Text = "Some comment text.<br> Comment line.",
                                         User = new User { UserId = 7, FirstName = "John", LastName = "Grey" }
                                     },
                                 Replies =
                                     new[]
                                     {
                                         new CommentViewModel
                                         {
                                             Comment =
                                                 new Comment
                                                 {
                                                     CommentId = 11, Date = new DateTime(2015, 2, 22, 17, 24, 45),
                                                     Text = "Some comment text.<br> Comment line.",
                                                     User =
                                                         new User
                                                         { UserId = 7, FirstName = "John", LastName = "Grey" }
                                                 },
                                             Replies =
                                                 new[]
                                                 {
                                                     new CommentViewModel
                                                     {
                                                         Comment =
                                                             new Comment
                                                             {
                                                                 CommentId = 12,
                                                                 Date = new DateTime(2015, 2, 22, 17, 24, 45),
                                                                 Text = "Some comment text.<br> Comment line.",
                                                                 User =
                                                                     new User
                                                                     {
                                                                         UserId = 7, FirstName = "John",
                                                                         LastName = "Grey"
                                                                     }
                                                             }
                                                     }
                                                 }
                                         }
                                     }
                             }
                         }
                 },
                 new CommentViewModel
                 {
                     Comment =
                         new Comment
                         {
                             CommentId = 13, Date = new DateTime(2015, 2, 22, 17, 24, 45),
                             Text = "Some comment text.<br> Comment line.",
                             User = new User { UserId = 7, FirstName = "John", LastName = "Grey" }
                         }
                 }
             }
     };
 }
        public virtual ActionResult ChangeLanguage(long articleId, String culture)
        {
            var article = articleService.Find(articleId);

            if (article == null || !permissionService.IsAllowed((Int32)ArticleOperations.View, this.CorePrincipal(), typeof(Article), article.Id, IsArticleOwner(article), PermissionOperationLevel.Object))
            {
                throw new HttpException((int)HttpStatusCode.NotFound, HttpContext.Translate("Messages.NotFound", ResourceHelper.GetControllerScope(this)));
            }

            bool allowManage = permissionService.IsAllowed((Int32)ArticleOperations.Manage, this.CorePrincipal(),
                                                        typeof(Article), article.Id, IsArticleOwner(article),
                                                        PermissionOperationLevel.Object);

            ArticleViewModel model = new ArticleViewModel { AllowManage = allowManage }.MapFrom(article);
            model.SelectedCulture = culture;

            //get locale
            var localeService = ServiceLocator.Current.GetInstance<IArticleLocaleService>();
            ArticleLocale locale = localeService.GetLocale(articleId, culture);

            if (locale != null)
                model.MapLocaleFrom(locale);

            return PartialView("ArticleDetails", model);
        }