Exemplo n.º 1
0
        public int SaveOrUpdate(BlogPostModel entity)
        {
            if (entity.ID != 0)
            {
                var dbEntity = BlogPostRepository.Get(entity.ID);
                if (dbEntity != null)
                {
                    BlogPostRepository.Update(dbEntity);

                    return dbEntity.ID;
                }
                throw new ArgumentException("Invalid id");
            }
            return BlogPostRepository.Save(entity);
        }
        public ActionResult BlogsHome()
        {
            var model = new BlogPostListModel();

            model.WorkingLanguageId = _workContext.WorkingLanguage.Id;
            var blogPosts = _blogService.GetNewBlogPosts();

            model.BlogPosts = blogPosts
                              .Select(x =>
            {
                var blogPostModel = new BlogPostModel();
                PrepareBlogPostModel(blogPostModel, x, false);
                return(blogPostModel);
            })
                              .ToList();
            return(PartialView(model));
        }
        public ActionResult Create()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageBlog))
            {
                return(AccessDeniedView());
            }

            var model = new BlogPostModel();

            //languages
            PrepareLanguagesModel(model);
            //Stores
            PrepareStoresMappingModel(model, null, false);
            //default values
            model.AllowComments = true;
            return(View(model));
        }
        /// <summary>
        /// Prepare blog post model
        /// </summary>
        /// <param name="model">Blog post model</param>
        /// <param name="blogPost">Blog post entity</param>
        /// <param name="prepareComments">Whether to prepare blog comments</param>
        public virtual void PrepareBlogPostModel(BlogPostModel model, BlogPost blogPost, bool prepareComments)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (blogPost == null)
            {
                throw new ArgumentNullException(nameof(blogPost));
            }

            model.Id              = blogPost.Id;
            model.MetaTitle       = blogPost.MetaTitle;
            model.MetaDescription = blogPost.MetaDescription;
            model.MetaKeywords    = blogPost.MetaKeywords;
            model.SeName          = _urlRecordService.GetSeName(blogPost, blogPost.LanguageId, ensureTwoPublishedLanguages: false);
            model.Title           = blogPost.Title;
            model.Body            = blogPost.Body;
            model.BodyOverview    = blogPost.BodyOverview;
            model.AllowComments   = blogPost.AllowComments;
            model.CreatedOn       = _dateTimeHelper.ConvertToUserTime(blogPost.StartDateUtc ?? blogPost.CreatedOnUtc, DateTimeKind.Utc);
            model.Tags            = _blogService.ParseTags(blogPost);
            model.AddNewComment.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage;

            //number of blog comments
            var storeId  = _blogSettings.ShowBlogCommentsPerStore ? _storeContext.CurrentStore.Id : 0;
            var cacheKey = string.Format(NopModelCacheDefaults.BlogCommentsNumberKey, blogPost.Id, storeId, true);

            model.NumberOfComments = _cacheManager.Get(cacheKey, () => _blogService.GetBlogCommentsCount(blogPost, storeId, true));

            if (prepareComments)
            {
                var blogComments = blogPost.BlogComments.Where(comment => comment.IsApproved);
                if (_blogSettings.ShowBlogCommentsPerStore)
                {
                    blogComments = blogComments.Where(comment => comment.StoreId == _storeContext.CurrentStore.Id);
                }

                foreach (var bc in blogComments.OrderBy(comment => comment.CreatedOnUtc))
                {
                    var commentModel = PrepareBlogPostCommentModel(bc);
                    model.Comments.Add(commentModel);
                }
            }
        }
Exemplo n.º 5
0
        public ActionResult Edit(BlogPostModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageBlog))
            {
                return(AccessDeniedView());
            }

            var blogPost = _blogService.GetBlogPostById(model.Id);

            if (blogPost == null)
            {
                //No blog post found with the specified id
                return(RedirectToAction("List"));
            }

            if (ModelState.IsValid)
            {
                blogPost = model.ToEntity(blogPost);
                blogPost.StartDateUtc = model.StartDate;
                blogPost.EndDateUtc   = model.EndDate;
                _blogService.UpdateBlogPost(blogPost);

                //search engine name
                var seName = blogPost.ValidateSeName(model.SeName, model.Title, true);
                _urlRecordService.SaveSlug(blogPost, seName, blogPost.LanguageId);

                //Stores
                SaveStoreMappings(blogPost, model);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.Blog.BlogPosts.Updated"));
                if (continueEditing)
                {
                    //selected tab
                    SaveSelectedTabIndex();

                    return(RedirectToAction("Edit", new { id = blogPost.Id }));
                }
                return(RedirectToAction("List"));
            }

            //If we got this far, something failed, redisplay form
            ViewBag.AllLanguages = _languageService.GetAllLanguages(true);
            //Store
            PrepareStoresMappingModel(model, blogPost, true);
            return(View(model));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Create(BlogPostModel model, bool continueEditing)
        {
            if (ModelState.IsValid)
            {
                var blogPost = await _blogViewModelService.InsertBlogPostModel(model);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.Blog.BlogPosts.Added"));
                return(continueEditing ? RedirectToAction("Edit", new { id = blogPost.Id }) : RedirectToAction("List"));
            }

            //If we got this far, something failed, redisplay form
            ViewBag.AllLanguages = await _languageService.GetAllLanguages(true);

            model = await _blogViewModelService.PrepareBlogPostModel(model);

            return(View(model));
        }
Exemplo n.º 7
0
        public ActionResult Create([Bind(Include = "Id,Subject,Content,Topic_Id")] BlogPostModel blogPostModel)
        {
            string    guid = Guid.Parse(User.Identity.GetUserId()).ToString();
            UserModel user = db.UserModels.FirstOrDefault(x => x.ApplicationUser_Id == guid);

            if (ModelState.IsValid)
            {
                blogPostModel.Id          = Guid.NewGuid();
                blogPostModel.User        = user;
                blogPostModel.CreatedDate = DateTime.Now;
                db.Posts.Add(blogPostModel);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(blogPostModel));
        }
Exemplo n.º 8
0
        public virtual ActionResult BlogPost(int blogPostId)
        {
            var blogPost = _blogService.GetBlogPostById(blogPostId);

            if (blogPost == null ||
                (blogPost.StartDateUtc.HasValue && blogPost.StartDateUtc.Value >= DateTime.UtcNow) ||
                (blogPost.EndDateUtc.HasValue && blogPost.EndDateUtc.Value <= DateTime.UtcNow))
            {
                return(RedirectToRoute("HomePage"));
            }

            var model = new BlogPostModel();

            _blogModelFactory.PrepareBlogPostModel(model, blogPost, true);

            return(View(model));
        }
Exemplo n.º 9
0
        public virtual IActionResult BlogPostCreate(BlogPostModel model, bool continueEditing)
        {
            bool isAuthorized = _authorizationService.AuthorizeAsync(User, GetCurrentUserAsync(), CustomerOperations.Create).Result.Succeeded;

            if (!isAuthorized)
            {
                return(AccessDeniedView());
            }

            if (ModelState.IsValid)
            {
                BlogPost blogPost = model.ToEntity <BlogPost>();
                blogPost.StartDateUtc = model.StartDate;
                blogPost.EndDateUtc   = model.EndDate;
                blogPost.CreatedOnUtc = DateTime.UtcNow;
                blogPost.CustomerId   = model.CustomerId;

                _blogService.InsertBlogPost(blogPost);

                //activity log
                _customerActivityService.InsertActivity("AddNewBlogPost",
                                                        string.Format("AddNewBlogPost{0}", blogPost.Id), blogPost);

                //search engine name
                string seName = _urlRecordService.ValidateSeName(blogPost, model.SeName, model.Title, true);
                _urlRecordService.SaveSlug(blogPost, seName);
                SuccessNotification("Yazı Eklendi");

                if (!continueEditing)
                {
                    return(RedirectToAction("List"));
                }

                //selected tab
                SaveSelectedTabName();

                return(RedirectToAction("BlogPostEdit", new { id = blogPost.Id }));
            }

            //prepare model
            model = _blogModelFactory.PrepareBlogPostModel(model, null, true);

            //if we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 10
0
        public virtual IActionResult BlogPostCreate(BlogPostModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageBlog))
            {
                return(AccessDeniedView());
            }

            if (ModelState.IsValid)
            {
                var blogPost = model.ToEntity <BlogPost>();
                blogPost.StartDateUtc = model.StartDate;
                blogPost.EndDateUtc   = model.EndDate;
                blogPost.CreatedOnUtc = DateTime.UtcNow;
                _blogService.InsertBlogPost(blogPost);

                //activity log
                _customerActivityService.InsertActivity("AddNewBlogPost",
                                                        string.Format(_localizationService.GetResource("ActivityLog.AddNewBlogPost"), blogPost.Id), blogPost);

                //search engine name
                var seName = _urlRecordService.ValidateSeName(blogPost, model.SeName, model.Title, true);
                _urlRecordService.SaveSlug(blogPost, seName, blogPost.LanguageId);

                //Stores
                SaveStoreMappings(blogPost, model);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.Blog.BlogPosts.Added"));

                if (!continueEditing)
                {
                    return(RedirectToAction("List"));
                }

                //selected tab
                SaveSelectedTabName();

                return(RedirectToAction("BlogPostEdit", new { id = blogPost.Id }));
            }

            //prepare model
            model = _blogModelFactory.PrepareBlogPostModel(model, null, true);

            //if we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 11
0
        protected BlogPostListModel PrepareBlogPostListModel(int?maxPostAmount, int?maxAgeInDays, bool renderHeading, string blogHeading, bool disableCommentCount, string postsWithTag)
        {
            var storeId    = _services.StoreContext.CurrentStore.Id;
            var languageId = _services.WorkContext.WorkingLanguage.Id;
            var isAdmin    = _services.WorkContext.CurrentCustomer.IsAdmin();

            var model = new BlogPostListModel
            {
                BlogHeading         = blogHeading,
                RenderHeading       = renderHeading,
                RssToLinkButton     = renderHeading,
                DisableCommentCount = disableCommentCount
            };

            DateTime?maxAge = null;

            if (maxAgeInDays.HasValue)
            {
                maxAge = DateTime.UtcNow.AddDays(-maxAgeInDays.Value);
            }

            IPagedList <BlogPost> blogPosts;

            if (!postsWithTag.IsEmpty())
            {
                blogPosts = _blogService.GetAllBlogPostsByTag(storeId, postsWithTag, 0, maxPostAmount ?? 100, languageId, isAdmin, maxAge);
            }
            else
            {
                blogPosts = _blogService.GetAllBlogPosts(storeId, null, null, 0, maxPostAmount ?? 100, languageId, isAdmin, maxAge);
            }

            Services.DisplayControl.AnnounceRange(blogPosts);

            model.BlogPosts = blogPosts
                              .Select(x =>
            {
                var blogPostModel = new BlogPostModel();
                PrepareBlogPostModel(blogPostModel, x, false);
                return(blogPostModel);
            })
                              .ToList();

            return(model);
        }
Exemplo n.º 12
0
        [HttpPost, ActionName("Create")]  //Using create get branch
        public ActionResult BlogText(BlogPostModel model)
        {
            //DB change--> Allow nulls --> UserId, IsVisible
            var blogPost = new BlogPost();

            // Using viewbag for get the colors for the view.
            ViewBag.FontColorId       = new SelectList(db.Color, "Id", "Name");
            ViewBag.BackgroundColorId = new SelectList(db.Color, "Id", "Name");
            // Validation if the two color is the same.
            if (model.FontColorId == model.BackgroundColorId)
            {
                ModelState.AddModelError("FontColorId", "A háttér és a betű színe azonos!");

                return(View(model));
            }

            if (ModelState.IsValid)
            {
                // Mapping here -->
                blogPost.UserId            = int.Parse(Session["Id"].ToString()); // Write posts only logged in state.
                blogPost.Title             = model.Title;
                blogPost.Text              = model.Text;
                blogPost.IsVisible         = model.IsVisible;
                blogPost.FontSize          = model.FontSize;
                blogPost.FontColorId       = model.FontColorId;
                blogPost.BackgroundColorId = model.BackgroundColorId;
                // Adding the image here.
                if (model.DataInHttpPostedFileBase != null && model.Image != null)
                {
                    blogPost.Image = ConvertHttpPostedFileBaseToByteArray(model.DataInHttpPostedFileBase);
                }

                db.BlogPost.Add(blogPost);
                db.SaveChanges();

                // Using TempData for JavaScript (show alert message)
                //..Scripts/MessageForUser
                TempData["postSaved"] = "showMessage";


                return(RedirectToAction("BlogList"));
            }

            return(View("Create")); // Else--> The validation failed.
        }
Exemplo n.º 13
0
        public ActionResult Create()
        {
            if (Request.HttpMethod == "POST")
            {
                // Post request method  
                var title = Request.Form["title"].ToString();
                var tags = Request.Form["tags"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var content = Request.Form["content"].ToString();

                // Save content  
                var post = new BlogPostModel { Title = title, CreateTime = DateTime.Now, Content = content, Tags = tags.ToList() };
                PostManager.Create(JsonConvert.SerializeObject(post));

                // Redirect  
                Response.Redirect("~/blog");
            }
            return View();
        }
        public ActionResult Index()
        {
            var post      = new BlogPost();
            var bpDao     = new BlogPostDAO();
            var listBlog  = bpDao.GetAllBlogPost();
            var Listmodel = new List <BlogPostModel>();

            foreach (var item in listBlog.ToList())
            {
                var model = new BlogPostModel();
                model.BlogPostID = item.BlogPostID;
                model.Body       = item.Body;
                model.Title      = item.Title;
                Listmodel.Add(model);
            }
            //var blogmodel = model as IEnumerable<BlogPostModel>;
            return(View(Listmodel));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Prepare blog post model
        /// </summary>
        /// <param name="model">Blog post model</param>
        /// <param name="blogPost">Blog post</param>
        /// <param name="excludeProperties">Whether to exclude populating of some properties of model</param>
        /// <returns>Blog post model</returns>
        public virtual BlogPostModel PrepareBlogPostModel(BlogPostModel model, BlogPost blogPost, bool excludeProperties = false)
        {
            //fill in model values from the entity
            if (blogPost != null)
            {
                model           = model ?? blogPost.ToModel <BlogPostModel>();
                model.StartDate = blogPost.StartDateUtc;
                model.EndDate   = blogPost.EndDateUtc;
            }

            //set default values for the new model
            if (blogPost == null)
            {
                model.AllowComments = true;
            }
            _baseAdminModelFactory.PrepareEditorList(model.AvailableEditors, true, "Editor Seçiniz");
            return(model);
        }
Exemplo n.º 16
0
        protected virtual void PrepareLanguagesModel(BlogPostModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var languages = _languageService.GetAllLanguages(true);

            foreach (var language in languages)
            {
                model.AvailableLanguages.Add(new SelectListItem
                {
                    Text  = language.Name,
                    Value = language.Id.ToString()
                });
            }
        }
Exemplo n.º 17
0
        public ActionResult AddPost(BlogPostModel blogPost)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new ApplicationException("Bad values.");
                }
                var newBp = blogPost.AsBlogPost();
                _dataAccess.AddBlogPost(newBp);

                return(RedirectToAction("Index", "Home"));
            }
            catch (Exception ex)
            {
                return(View("Error", ex));
            }
        }
Exemplo n.º 18
0
        // GET: Blog/Details/id
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            BlogPostModel blogPostModel = db.BlogPostTable.Find(id);

            if (blogPostModel == null)
            {
                return(HttpNotFound());
            }

            DirectoryInfo     uploadedImagesDirectory = new DirectoryInfo(Server.MapPath("~/UploadedImages/"));
            BlogPostViewModel bpViewModel             = new BlogPostViewModel(blogPostModel, uploadedImagesDirectory);

            return(View(bpViewModel));
        }
Exemplo n.º 19
0
        public async Task <IActionResult> Edit(BlogPostModel model, bool continueEditing)
        {
            var blogPost = await _blogService.GetBlogPostById(model.Id);

            if (blogPost == null)
            {
                //No blog post found with the specified id
                return(RedirectToAction("List"));
            }

            if (ModelState.IsValid)
            {
                blogPost = await _blogViewModelService.UpdateBlogPostModel(model, blogPost);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.Blog.BlogPosts.Updated"));
                if (continueEditing)
                {
                    //selected tab
                    await SaveSelectedTabIndex();

                    return(RedirectToAction("Edit", new { id = blogPost.Id }));
                }
                return(RedirectToAction("List"));
            }

            //If we got this far, something failed, redisplay form
            ViewBag.AllLanguages = await _languageService.GetAllLanguages(true);

            model = await _blogViewModelService.PrepareBlogPostModel(model, blogPost);

            //locales
            await AddLocales(_languageService, model.Locales, (locale, languageId) =>
            {
                locale.Title           = blogPost.GetLocalized(x => x.Title, languageId, false, false);
                locale.Body            = blogPost.GetLocalized(x => x.Body, languageId, false, false);
                locale.BodyOverview    = blogPost.GetLocalized(x => x.BodyOverview, languageId, false, false);
                locale.MetaKeywords    = blogPost.GetLocalized(x => x.MetaKeywords, languageId, false, false);
                locale.MetaDescription = blogPost.GetLocalized(x => x.MetaDescription, languageId, false, false);
                locale.MetaTitle       = blogPost.GetLocalized(x => x.MetaTitle, languageId, false, false);
                locale.SeName          = blogPost.GetSeName(languageId, false, false);
            });

            return(View(model));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Prepare paged blog post list model
        /// </summary>
        /// <param name="searchModel">Blog post search model</param>
        /// <param name="customerId"></param>
        /// <returns>Blog post list model</returns>
        public virtual BlogPostListModel PrepareBlogPostListModel(BlogPostSearchModel searchModel, int customerId = 0)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get blog posts
            var blogPosts = _blogService.GetAllBlogPosts(customerId: customerId, showHidden: true,
                                                         pageIndex: searchModel.Page - 1, pageSize: searchModel.PageSize);

            //prepare list model
            BlogPostListModel model = new BlogPostListModel
            {
                Data = blogPosts.Select(blogPost =>
                {
                    //fill in model values from the entity
                    BlogPostModel blogPostModel = blogPost.ToModel <BlogPostModel>();

                    //little performance optimization: ensure that "Body" is not returned
                    blogPostModel.Body = string.Empty;

                    //convert dates to the user time
                    if (blogPost.StartDateUtc.HasValue)
                    {
                        blogPostModel.StartDate = blogPost.StartDateUtc.Value;
                    }
                    if (blogPost.EndDateUtc.HasValue)
                    {
                        blogPostModel.EndDate = blogPost.EndDateUtc.Value;
                    }
                    blogPostModel.CreatedOn = blogPost.CreatedOnUtc;

                    //fill in additional values (not existing in the entity)
                    blogPostModel.ApprovedComments    = _blogService.GetBlogCommentsCount(blogPost, isApproved: true);
                    blogPostModel.NotApprovedComments = _blogService.GetBlogCommentsCount(blogPost, isApproved: false);

                    return(blogPostModel);
                }),
                Total = blogPosts.TotalCount
            };

            return(model);
        }
Exemplo n.º 21
0
        public ActionResult Edit(BlogPostModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageBlog))
            {
                return(AccessDeniedView());
            }

            var blogPost = _blogService.GetBlogPostById(model.Id);

            if (blogPost.CustomerId != _workContext.CurrentCustomer.Id)
            {
                return(AccessDeniedView());
            }
            if (blogPost == null)
            {
                return(RedirectToAction("List"));
            }

            if (ModelState.IsValid)
            {
                blogPost = model.ToEntity(blogPost);
                blogPost.CreatedOnUtc = model.CreatedOnUtc;
                blogPost.StartDateUtc = model.StartDate;
                blogPost.EndDateUtc   = model.EndDate;
                blogPost.CustomerId   = _workContext.CurrentCustomer.Id;
                _blogService.UpdateBlogPost(blogPost);

                //search engine name
                var seName = blogPost.ValidateSeName(model.SeName, model.Title, true);
                _urlRecordService.SaveSlug(blogPost, seName, blogPost.LanguageId);

                //Stores
                _storeMappingService.SaveStoreMappings <BlogPost>(blogPost, model.SelectedStoreIds);

                NotifySuccess(_localizationService.GetResource("Admin.ContentManagement.Blog.BlogPosts.Updated"));
                return(continueEditing ? RedirectToAction("Edit", new { id = blogPost.Id }) : RedirectToAction("List"));
            }

            //If we got this far, something failed, redisplay form
            ViewBag.AllLanguages = _languageService.GetAllLanguages(true);
            //Store
            PrepareStoresMappingModel(model, blogPost, true);
            return(View(model));
        }
Exemplo n.º 22
0
        public async Task <IActionResult> Create(BlogPostModel model, bool continueEditing)
        {
            if (ModelState.IsValid)
            {
                if (await _groupService.IsStaff(_workContext.CurrentCustomer))
                {
                    model.Stores = new string[] { _workContext.CurrentCustomer.StaffStoreId };
                }
                var blogPost = await _blogViewModelService.InsertBlogPostModel(model);

                Success(_translationService.GetResource("Admin.Content.Blog.BlogPosts.Added"));
                return(continueEditing ? RedirectToAction("Edit", new { id = blogPost.Id }) : RedirectToAction("List"));
            }

            //If we got this far, something failed, redisplay form
            ViewBag.AllLanguages = await _languageService.GetAllLanguages(true);

            return(View(model));
        }
Exemplo n.º 23
0
        public ActionResult Create(BlogPostModel model)
        {
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    //este modelo se enviara a crear, luego se enviara al MODELO de BlogPostModel (y despues de ahi a la DB)
                    _repo.Crear(model);

                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                //log ex
            }
            return(View(model));
        }
Exemplo n.º 24
0
 public int Update(BlogPostModel entity)
 {
     try
     {
         if (entity != null)
         {
             int id     = entity.Id;
             var record = _BlogPostRepository.Get(id);
             _BlogPostRepository.Update(Convert(entity, record));
             TriggerSignal();
             return(id);
         }
     }
     catch (Exception ex)
     {
         Logger.Error(ex, "Update BlogPost failed, entity: {0}", JObject.FromObject(entity));
     }
     return(-1);
 }
Exemplo n.º 25
0
        private IEnumerable <BlogPostModel> ConvertPosts(IEnumerable <string> files)
        {
            var posts = new List <BlogPostModel>();

            var blogPostConverter = new BlogPostConverter(topLevelConfig, handlebarsConverter);

            foreach (string postSourceFile in files)
            {
                BlogPostModel blogPost = blogPostConverter.ProcessBlogPost(postSourceFile);
                LogInfo($"Converted {postSourceFile} to HTML");

                if (blogPost != null)
                {
                    posts.Add(blogPost);
                }
            }

            return(posts);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Prepare blog post list model
        /// </summary>
        /// <param name="command">Blog paging filtering model</param>
        /// <returns>Blog post list model</returns>
        public virtual async Task <BlogPostListModel> PrepareBlogPostListModelAsync(BlogPagingFilteringModel command)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            if (command.PageSize <= 0)
            {
                command.PageSize = _blogSettings.PostsPageSize;
            }
            if (command.PageNumber <= 0)
            {
                command.PageNumber = 1;
            }

            var dateFrom = command.GetFromMonth();
            var dateTo   = command.GetToMonth();

            var language = await _workContext.GetWorkingLanguageAsync();

            var store = await _storeContext.GetCurrentStoreAsync();

            var blogPosts = string.IsNullOrEmpty(command.Tag)
                ? await _blogService.GetAllBlogPostsAsync(store.Id, language.Id, dateFrom, dateTo, command.PageNumber - 1, command.PageSize)
                : await _blogService.GetAllBlogPostsByTagAsync(store.Id, language.Id, command.Tag, command.PageNumber - 1, command.PageSize);

            var model = new BlogPostListModel
            {
                PagingFilteringContext = { Tag = command.Tag, Month = command.Month },
                WorkingLanguageId      = language.Id,
                BlogPosts = await blogPosts.SelectAwait(async blogPost =>
                {
                    var blogPostModel = new BlogPostModel();
                    await PrepareBlogPostModelAsync(blogPostModel, blogPost, false);
                    return(blogPostModel);
                }).ToListAsync()
            };

            model.PagingFilteringContext.LoadPagedList(blogPosts);

            return(model);
        }
Exemplo n.º 27
0
        protected virtual void PrepareStoresMappingModel(BlogPostModel model, BlogPost blogPost, bool excludeProperties)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            model.AvailableStores = _storeService
                                    .GetAllStores()
                                    .Select(s => s.ToModel())
                                    .ToList();
            if (!excludeProperties)
            {
                if (blogPost != null)
                {
                    model.SelectedStoreIds = blogPost.Stores.ToArray();
                }
            }
        }
Exemplo n.º 28
0
        public async Task PrepareBlogPostModelDisplayCaptchaShouldBeDependOnSettings()
        {
            var model    = new BlogPostModel();
            var blogPost = await _blogService.GetBlogPostByIdAsync(1);

            await _blogModelFactory.PrepareBlogPostModelAsync(model, blogPost, false);

            model.AddNewComment.DisplayCaptcha.Should().BeFalse();

            _captchaSettings.Enabled = _captchaSettings.ShowOnBlogCommentPage = true;
            await _settingsService.SaveSettingAsync(_captchaSettings);

            await GetService <IBlogModelFactory>().PrepareBlogPostModelAsync(model, blogPost, false);

            _captchaSettings.Enabled = _captchaSettings.ShowOnBlogCommentPage = false;
            await _settingsService.SaveSettingAsync(_captchaSettings);

            model.AddNewComment.DisplayCaptcha.Should().BeTrue();
        }
Exemplo n.º 29
0
        public void AddPostAddPost()
        {
            AddPostController controller = new AddPostController(_dataAccess);
            var blogPost = new BlogPostModel()
            {
                Post  = "The post",
                Title = "The title"
            };
            RedirectToRouteResult result = controller.AddPost(blogPost) as RedirectToRouteResult;

            Assert.IsNotNull(result);
            Assert.AreEqual("Home", result.RouteValues["controller"]);
            Assert.AreEqual("Index", result.RouteValues["action"]);
            var bp = _dataAccess.GetBlogPost(3);

            Assert.AreEqual(0, bp.Comments.Count);
            Assert.AreEqual("The post", bp.Post);
            Assert.AreEqual("The title", bp.Title);
        }
Exemplo n.º 30
0
        // GET: BlogPosts/Details/5
        public async Task <IActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            BlogPostModel blogPostModel = await _context.BlogPostModel
                                          .SingleOrDefaultAsync(m => m.ID == id);

            if (blogPostModel == null)
            {
                return(NotFound());
            }

            BlogPostCommentsViewModel viewModel = await GetBlogPostCommentsViewModelFromBlogPost(blogPostModel);

            return(View(viewModel));
        }
Exemplo n.º 31
0
        public EditorListModel PrePareEditorListModel()
        {
            var model      = new EditorListModel();
            var editorList = _customerService.GetRolesApplicationUsers(CustomerRole.Constants.CustomerManagersRole);

            foreach (var customer in editorList)
            {
                var appUser = _customerService.GetApplicationUserById(customer.OwnerId);

                var editor = new EditorModel();
                editor.AvatarUrl = _pictureService.GetPictureUrl(Convert.ToInt32(_customerService.GetCustomerById(customer.Id).Zip), 120, defaultPictureType: PictureType.Avatar);
                editor.Email     = appUser.Email;
                editor.FirstName = appUser.FirstName;
                editor.LastName  = appUser.LastName;
                editor.EditorId  = customer.Id;
                var claimsAsync = _customerService.GetUserClaim(customer.OwnerId);
                foreach (var item in claimsAsync)
                {
                    if (item.ClaimType == "FacebookLink")
                    {
                        editor.FaceBookLink = item.ClaimValue ?? "";
                    }
                    else if (item.ClaimType == "InstagramLink")
                    {
                        editor.InstagramLink = item.ClaimValue ?? "";
                    }
                    else if (item.ClaimType == "TwitterLink")
                    {
                        editor.TwitterLink = item.ClaimValue ?? "";
                    }
                }
                model.EditorModels.Add(editor);
                var blog      = _blogservice.GetAllBlogPosts(customerId: editor.EditorId).LastOrDefault();
                var blogModel = new BlogPostModel();
                if (blog != null)
                {
                    PrepareBlogPostModel(blogModel, blog, false);
                }

                editor.BlogPostModel = blogModel;
            }
            return(model);
        }
Exemplo n.º 32
0
        private void PrepareStoresMappingModel(BlogPostModel model, BlogPost blogPost, bool excludeProperties)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            model.AvailableStores = _storeService
                .GetAllStores()
                .Select(s => s.ToModel())
                .ToList();
            if (!excludeProperties)
            {
                if (blogPost != null)
                {
                    model.SelectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(blogPost);
                }
                else
                {
                    model.SelectedStoreIds = new int[0];
                }
            }
        }
Exemplo n.º 33
0
 public IHttpActionResult Save(BlogPostModel item)
 {
     try
     {
         if (item != null)
         {
             BlogPostService.SaveOrUpdate(item);
             return Ok(item);
         }
         return BadRequest("No se ha enviado información que almacenar.");
     }
     catch (HibernateAdoException hibernateException)
     {
         if (hibernateException.InnerException is GenericADOException)
         {
             if (hibernateException.InnerException.InnerException is OracleException)
             {
                 return InternalServerError(hibernateException.InnerException.InnerException);
             }
             return InternalServerError(hibernateException.InnerException);
         }
         return InternalServerError(hibernateException);
     }
     catch (Exception exception)
     {
         return InternalServerError(exception);
     }
 }
Exemplo n.º 34
0
        public ActionResult Edit(BlogPostModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageBlog))
                return AccessDeniedView();

            var blogPost = _blogService.GetBlogPostById(model.Id);
            if (blogPost == null)
                //No blog post found with the specified id
                return RedirectToAction("List");

            if (ModelState.IsValid)
            {
                blogPost = model.ToEntity(blogPost);
                blogPost.StartDateUtc = model.StartDate;
                blogPost.EndDateUtc = model.EndDate;
                _blogService.UpdateBlogPost(blogPost);

                //search engine name
                var seName = blogPost.ValidateSeName(model.SeName, model.Title, true);
                _urlRecordService.SaveSlug(blogPost, seName, blogPost.LanguageId);

                //Stores
                SaveStoreMappings(blogPost, model);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.Blog.BlogPosts.Updated"));
                return continueEditing ? RedirectToAction("Edit", new { id = blogPost.Id }) : RedirectToAction("List");
            }

            //If we got this far, something failed, redisplay form
            ViewBag.AllLanguages = _languageService.GetAllLanguages(true);
            //Store
            PrepareStoresMappingModel(model, blogPost, true);
            return View(model);
        }
Exemplo n.º 35
0
 public void Update(BlogPostModel entity)
 {
     BlogPostRepository.Update(entity);
 }
Exemplo n.º 36
0
 public int Save(BlogPostModel entity)
 {
     return BlogPostRepository.Save(entity);
 }
Exemplo n.º 37
0
        public ActionResult Create()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageBlog))
                return AccessDeniedView();

            ViewBag.AllLanguages = _languageService.GetAllLanguages(true);
            var model = new BlogPostModel();
            //Stores
            PrepareStoresMappingModel(model, null, false);
            //default values
            model.AllowComments = true;
            return View(model);
        }
Exemplo n.º 38
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="entity"></param>
 /// <returns></returns>
 public int Save(BlogPostModel entity)
 {
     return (int) CurrentSession.Save(entity);
 }
Exemplo n.º 39
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="entity"></param>
 public void Update(BlogPostModel entity)
 {
     CurrentSession.Update(entity);
 }
Exemplo n.º 40
0
 protected void SaveStoreMappings(BlogPost blogPost, BlogPostModel model)
 {
     var existingStoreMappings = _storeMappingService.GetStoreMappings(blogPost);
     var allStores = _storeService.GetAllStores();
     foreach (var store in allStores)
     {
         if (model.SelectedStoreIds != null && model.SelectedStoreIds.Contains(store.Id))
         {
             //new role
             if (existingStoreMappings.Count(sm => sm.StoreId == store.Id) == 0)
                 _storeMappingService.InsertStoreMapping(blogPost, store.Id);
         }
         else
         {
             //removed role
             var storeMappingToDelete = existingStoreMappings.FirstOrDefault(sm => sm.StoreId == store.Id);
             if (storeMappingToDelete != null)
                 _storeMappingService.DeleteStoreMapping(storeMappingToDelete);
         }
     }
 }