public ActionResult Add(BlogArticle blogArticle)
        {
            if (blogArticle.bID > 0)
            {
                BlogArticle model = BlogArticleServive.QueryWhere(a => a.bID == blogArticle.bID).FirstOrDefault();

                if (model != null)
                {
                    model.btitle    = blogArticle.btitle;
                    model.bcategory = blogArticle.bcategory;
                    model.bcontent  = blogArticle.bcontent;

                    BlogArticleServive.Edit(model);
                    BlogArticleServive.SaverChanges();
                    return(Content("<script type='text/javascript'>alert('厉害啦!更新成功!');window.location='/admin/BlogArticle/Index';</script>"));
                }
                else
                {
                    return(Content("<script type='text/javascript'>alert('错啦错啦,没这个数据!');window.location='/admin/BlogArticle/Add';</script>"));
                }
            }
            else
            {
                blogArticle.bCreateTime = DateTime.Now;
                blogArticle.bsubmitter  = "admin";
                blogArticle.bUpdateTime = DateTime.Now;
                blogArticle.bRemark     = string.Empty;
                BlogArticleServive.Add(blogArticle);
                BlogArticleServive.SaverChanges();
                return(Content("<script type='text/javascript'>alert('添加成功!');window.location='/admin/BlogArticle/Add';</script>"));
            }
        }
Example #2
0
        public async Task <MessageModel <string> > Put([FromBody] BlogArticle BlogArticle)
        {
            var data = new MessageModel <string>();

            if (BlogArticle != null && BlogArticle.bID > 0)
            {
                var model = await _blogArticleServices.QueryById(BlogArticle.bID);

                if (model != null)
                {
                    model.btitle     = BlogArticle.btitle;
                    model.bcategory  = BlogArticle.bcategory;
                    model.bsubmitter = BlogArticle.bsubmitter;
                    model.bcontent   = BlogArticle.bcontent;
                    model.btraffic   = BlogArticle.btraffic;

                    data.success = await _blogArticleServices.Update(model);

                    if (data.success)
                    {
                        data.msg      = "更新成功";
                        data.response = BlogArticle?.bID.ObjToString();
                    }
                }
            }

            return(data);
        }
        public async Task <MyBlogCommonResponse <int> > AddBlogArticle([FromBody] BlogArticle blogArticle)
        {
            MyBlogCommonResponse <int> response = new MyBlogCommonResponse <int>();

            try
            {
                blogArticle.ArticleCreateTime  = DateTime.Now;
                blogArticle.ArticleVisitNumber = 0;
                var id = (await _blogArticleServices.Add(blogArticle));
                response.success = id > 0;
                if (response.success)
                {
                    response.data    = id;
                    response.message = "添加成功";
                }
                else
                {
                    response.message = "执行数据添加失败"; response.code = 500;
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.message = ex.Message.ToString();
                response.code    = 500;
                return(response);
            }
        }
Example #4
0
        public async Task <ActionResult> Rss()
        {
            var sw = new StringWriter();

            using (XmlWriter xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings()
            {
                Async = true, Indent = true
            }))
            {
                var writer = new RssFeedWriter(xmlWriter);

                foreach (var art in BlogArticle.Queryable())
                {
                    // Create item
                    var item = new SyndicationItem()
                    {
                        Title       = art.Title,
                        Description = art.TextPreview,
                        Id          = $"https://matteofabbri.org/read/{art.Link}",
                        Published   = new DateTimeOffset(art.DateTime)
                    };

                    item.AddCategory(new SyndicationCategory(art.Category));
                    item.AddContributor(new SyndicationPerson("Matteo Fabbri", "*****@*****.**"));

                    await writer.Write(item);
                }

                xmlWriter.Flush();
            }
            return(Content(sw.ToString(), "application/rss+xml"));
        }
        public async Task <IActionResult> Edit(int id, [Bind("BlogArticleId,Title,BlogText")] BlogArticle blogArticle)
        {
            if (id != blogArticle.BlogArticleId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(blogArticle);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!BlogArticleExists(blogArticle.BlogArticleId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(blogArticle));
        }
Example #6
0
        // public ActionResult ArticleSave(string subject, string body)
        public ActionResult ArticleSave(BlogArticle model)
        { /*
           * var article = new BlogArticle();
           * // article.Subject = subject;
           * article.Subject = model.Subject;
           * // article.Body = body;
           * article.Body = model.Body;
           * article.CreTime = DateTime.Now;
           *
           * var db = new BlogDB();
           * db.BlogArticles.Add(article);
           * db.SaveChanges();*/
            if (ModelState.IsValid)
            {
                var article = new BlogArticle();
                article.Subject = model.Subject;
                article.Body    = model.Body;
                article.CreTime = DateTime.Now;

                var db = new BlogDB();
                db.BlogArticles.Add(article);
                db.SaveChanges();
            }
            return(Redirect("Index"));
            // return RedirectToAction("Index");
        }
        public void NewSaveTest()
        {
            //使用 IoCHelper 测试
            IArticleRepository  article  = IoCHelper.Resolve <IArticleRepository>();
            ICategoryRepository category = IoCHelper.Resolve <ICategoryRepository>();

            BlogArticle model    = new BlogArticle();
            int         expected = 0;
            int         actual   = 0;

            model.Title = "测试标题" + new Random().Next(100000, 999999).ToString();
            model.IsTop = true;

            //model.BlogCategory = category.GetByCondition(new DirectSpecification<BlogCategory>(x => x.CateID == 2));
            model.BlogCategory = category.GetList()[0];

            model.Content     = "这里是内容";
            model.PublishTime = DateTime.Now;
            model.CreateTime  = DateTime.Now;
            model.UpdateTime  = DateTime.Now;

            article.NewSave(model);
            article.SaveChanges();

            Assert.AreEqual(expected, actual);
        }
Example #8
0
        //public ActionResult ArticleSave(string subject, string body)
        public ActionResult ArticleSave(BlogArticle model)
        {
            //var article = new BlogArticle();
            // article.Subject = subject;
            //article.Body = body;
            //article.Subject = model.Subject;
            //article.Body = model.Body;
            //article.DateCreated = DateTime.Now;
            if (ModelState.IsValid)
            {
                var article = new BlogArticle();
                article.Subject     = model.Subject;
                article.Body        = model.Body;
                article.DateCreated = DateTime.Now;

                var db = new BlogDatabase();
                db.BlogArticles.Add(article);
                db.SaveChanges();
            }


            //var db = new BlogDatabase();
            //db.BlogArticles.Add(article);
            //db.SaveChanges();

            return(Redirect("Index"));
        }
        public async Task <IActionResult> Edit(int id, [Bind("CategoryId,Title,Content,AuthorId,IsDeleted,DeletedOn,Id,CreatedOn,ModifiedOn")] BlogArticle blogArticle)
        {
            if (id != blogArticle.Id)
            {
                return(this.NotFound());
            }

            if (this.ModelState.IsValid)
            {
                try
                {
                    this.dataRepository.Update(blogArticle);
                    await this.dataRepository.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!this.BlogArticleExists(blogArticle.Id))
                    {
                        return(this.NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }

                return(this.RedirectToAction(nameof(this.Index)));
            }

            this.ViewData["AuthorId"]   = new SelectList(this.userRepository.All(), "Id", "Id", blogArticle.AuthorId);
            this.ViewData["CategoryId"] = new SelectList(this.categoriesRepository.All(), "Id", "Id", blogArticle.CategoryId);
            return(this.View(blogArticle));
        }
Example #10
0
        public async Task <IActionResult> PostBlogArticle([FromBody] BlogArticle blogArticle)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                bool   flag     = false;
                string username = HttpContext.Session.GetString("UserName");
                if (!string.IsNullOrEmpty(username))
                {
                    blogArticle.bCreateTime = DateTime.Now;
                    flag = await blogArticleService.Add(blogArticle);
                }
                //清除缓存
                RedisCache.DeleteKeys("blog");

                return(Ok(new
                {
                    success = flag
                }));
            }
            catch (Exception ex)
            {
                loggerHelper.Error("BlogArticleController.PostBlogArticle", "异常位置:BlogArticleController.PostBlogArticle" + "异常消息:" + ex.Message);
                return(Ok(new
                {
                    success = false,
                    message = ex.Message
                }));
            }
        }
        public async Task <MyBlogCommonResponse <BlogArticle> > CreateNewBlogArticle(int id, int type)
        {
            MyBlogCommonResponse <BlogArticle> response = new MyBlogCommonResponse <BlogArticle>();

            try
            {
                BlogArticle blogArticle = new BlogArticle()
                {
                    ArticleCreateUserID   = id,
                    ArticleCreateTime     = DateTime.Now,
                    ArticleLastUpdateTime = DateTime.Now,
                    ArticleTitle          = DateTime.Now.ToString("yyyy-MM-dd"),
                    ArticleTechnicalType  = type,
                    ArticleVisitNumber    = 0,
                    ArticleStatus         = 1
                };
                var articleid = await _blogArticleServices.Add(blogArticle);

                blogArticle.ArticleId = articleid;
                response.code         = 200; response.success = true;
                response.data         = blogArticle;
                return(response);
            }
            catch (Exception ex)
            {
                response.message = ex.Message.ToString();
                response.code    = 500;
                return(response);
            }
        }
Example #12
0
 public async Task <int> AddAsync(BlogArticle blogarticle)
 {
     _context.BlogArticles.Add(new BlogArticle {
         ArticleTitle = blogarticle.ArticleTitle, ArticleContent = blogarticle.ArticleContent
     });
     return(await _context.SaveChangesAsync());
 }
        public static string GetUrl(this BlogArticle content, ContentReference reference)
        {
            var router    = new BlogPartialRouter(reference);
            var routeData = router.GetPartialVirtualPath(content, "en-us", null, null);

            return(routeData.PartialVirtualPath);
        }
Example #14
0
        public ActionResult Sitemap()
        {
            string baseUrl = "https://matteofabbri.org/";

            // get a list of published articles
            var posts = BlogArticle.Queryable();

            // get last modified date of the home page
            var siteMapBuilder = new SitemapBuilder();

            // add the home page to the sitemap
            siteMapBuilder.AddUrl(baseUrl, modified: DateTime.UtcNow, changeFrequency: ChangeFrequency.Weekly, priority: 1.0);

            // add the blog posts to the sitemap
            foreach (var post in posts)
            {
                siteMapBuilder.AddUrl($"{baseUrl}read/{post.Link}", modified: post.DateTime, changeFrequency: null, priority: 0.9);
            }

            siteMapBuilder.AddUrl($"{baseUrl}/privacy", modified: DateTime.UtcNow, changeFrequency: ChangeFrequency.Weekly, priority: 1.0);
            siteMapBuilder.AddUrl($"{baseUrl}/stat", modified: DateTime.UtcNow, changeFrequency: ChangeFrequency.Weekly, priority: 1.0);

            // generate the sitemap xml
            string xml = siteMapBuilder.ToString();

            return(Content(xml, "text/xml"));
        }
Example #15
0
        public async Task <IActionResult> Edit(BlogArticleEditModel model)
        {
            BlogArticle blogArticle = _database.BlogArticles.FirstOrDefault(b => b.Id == model.Id);

            blogArticle.Name = model.Name;
            blogArticle.Text = model.Text;

            string[] tags = null;
            if (!String.IsNullOrEmpty(model.TagsInput))
            {
                tags = model.TagsInput.Split(',');
            }
            if (tags != null)
            {
                foreach (var item in tags)
                {
                    blogArticle.Tags.Add(new Tag {
                        Name = item
                    });
                }
            }

            if (model.Image != null)
            {
                blogArticle.Image            = BlogHelper.ImageToByteArray(model.Image);
                blogArticle.ImageContentType = model.Image.ContentType;
            }
            await _database.SaveChangesAsync();

            return(RedirectToAction("Details", "BlogArticle", new { id = blogArticle.Id }));
        }
        public async Task <IActionResult> Edit(int id, [Bind("bID,bAuthor,bTitle,bContent,bCreateTime,bReadNum,bCommentNum,cID")] BlogArticle blogArticle)
        {
            if (id != blogArticle.bID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(blogArticle);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!BlogArticleExists(blogArticle.bID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(blogArticle));
        }
Example #17
0
 public void FillArticleForm(BlogArticle article)
 {
     CreateArticleBttn.Click();
     Type(Title, article.Title);
     Type(Content, article.Content);
     BttnSubmitArticle.Click();
 }
        public ContentItem GetItemFromPath(string path)
        {
            ContentItem retVal = null;

            if (!string.IsNullOrEmpty(path))
            {
                //Blog
                var blogMatch = _blogMatchRegex.Match(path);
                if (blogMatch.Success)
                {
                    var blogName = blogMatch.Groups["blog"].Value;
                    var fileName = Path.GetFileNameWithoutExtension(path);
                    if (fileName.EqualsInvariant(blogName) || fileName.EqualsInvariant("default"))
                    {
                        retVal = new Blog
                        {
                            Name = blogName,
                        };
                    }
                    else
                    {
                        retVal = new BlogArticle
                        {
                            BlogName = blogName
                        };
                    }
                }
                else
                {
                    retVal = new ContentPage();
                }
            }

            return(retVal);
        }
Example #19
0
        public ActionResult Create([Bind(Include = "Id,Title,Body,MediaUrl,Published")] BlogArticle blogArticle, HttpPostedFileBase image)
        {
            if (ModelState.IsValid)
            {
                var Slug = StringUtilities.URLFriendly(blogArticle.Title);
                if (String.IsNullOrWhiteSpace(Slug))
                {
                    ModelState.AddModelError("Title", "Invalid title.");
                    return(View(blogArticle));
                }
                if (db.Article.Any(p => p.Slug == Slug))
                {
                    ModelState.AddModelError("Title", "The title must be unique.");
                    return(View(blogArticle));
                }
                if (image != null)
                {
                    if (image.ContentLength > 0)
                    {
                        var fileName      = Path.GetFileName(image.FileName);
                        var fileExtension = Path.GetExtension(fileName);
                        if ((fileExtension == ".jpg") || (fileExtension == ".gif") || (fileExtension == ".png"))
                        {
                            var path = Server.MapPath("~/img/Blog/");
                            // if directory doesnt exist, create it
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }
                            else
                            // if directory exists, check if file exists in directory
                            {
                                if (Directory.Exists(fileName))
                                {
                                    blogArticle.MediaUrl = "/img/Blog/" + fileName;
                                }
                                else
                                {
                                    blogArticle.MediaUrl = "/img/Blog/" + fileName;
                                    image.SaveAs(Path.Combine(path, fileName));
                                }
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("image", "Invalid image extension. Only .gif, .jpg, and .png are allowed");
                            return(View(blogArticle));
                        }
                    }
                }
                blogArticle.CreateDate = DateTimeOffset.Now;
                blogArticle.UpdateDate = DateTimeOffset.Now;
                blogArticle.Slug       = Slug;
                db.Article.Add(blogArticle);
                db.SaveChanges();
            }

            return(RedirectToAction("Index"));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="BlogArticleShortResponse"/> class.
 /// </summary>
 /// <param name="blogArticle">A <see cref="BlogArticle"/>.</param>
 /// <param name="employee">An <see cref="Employee"/>.</param>
 public BlogArticleShortResponse(BlogArticle blogArticle, Employee employee)
 {
     this.Id             = blogArticle.BlogArticleId;
     this.Title          = blogArticle.Title;
     this.PulicationDate = blogArticle.PublicationDate;
     this.EmployeeId     = blogArticle.EmployeeId;
     this.AuthorName     = $"{employee.LastName} {employee.FirstName}";
 }
 public bool Del(BlogArticle blogArticle)
 {
     using (Conn)
     {
         string deletestr = "DELETE FROM BlogArticle WHERE BlogID = @BlogID";
         return(Conn.Execute(deletestr, blogArticle) > 0 ? true : false);
     }
 }
Example #22
0
        public ActionResult DeleteConfirmed(int id)
        {
            BlogArticle blogArticle = db.Article.Find(id);

            db.Article.Remove(blogArticle);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public bool Update(BlogArticle blogArticle)
 {
     using (Conn)
     {
         string query = "UPDATE BlogArticle SET Title=@Title,Keywords=@Keywords,Creator=@Creator,BlogContent=@BlogContent,BlogCreateTime=@BlogCreateTime,";
         return(Conn.Execute(query, blogArticle) > 0 ? true : false);
     }
 }
 public int Add(BlogArticle blogArticle)
 {
     using (Conn)
     {
         string query = "INSERT INTO BlogArticle(Title,Keywords,Creator,BlogContent,BlogCreateTime)VALUES(@Title,@Keywords,@Creator,@BlogContent,@BlogCreateTime)";
         return(Conn.Execute(query, blogArticle));
     }
 }
Example #25
0
        public async Task UpdateAsync(BlogArticle blogarticle)
        {
            _context.Attach(blogarticle);
            var entry = _context.Entry(blogarticle);

            entry.Property(e => e.ArticleTitle).IsModified   = true;
            entry.Property(e => e.ArticleContent).IsModified = true;
            await _context.SaveChangesAsync();
        }
Example #26
0
        public ActionResult Article(BlogArticle blogArticle)
        {
#if FILES_TO_FILESYSTEM
            _blogService.CreateArticle(blogArticle, HttpContext.Server.MapPath("~/Files"));
#else
            _blogService.CreateArticle(blogArticle);
#endif
            return(View());
        }
Example #27
0
        public async Task <MessageModel <string> > AddForMVP([FromBody] BlogArticle blogArticle)
        {
            blogArticle.bCreateTime = DateTime.Now;
            blogArticle.bUpdateTime = DateTime.Now;
            blogArticle.IsDeleted   = false;
            var id = (await _blogArticleServices.Add(blogArticle));

            return(id > 0 ? Success <string>(id.ObjToString()) : Failed("添加失败"));
        }
Example #28
0
        public ActionResult PostView(int id)
        {
            ISpecification <BlogArticle> condition = new DirectSpecification <BlogArticle>(x => x.ArticleID == id);

            BlogArticle model = _articleService.GetByCondition(condition);

            ViewData["model"] = model;
            return(View());
        }
Example #29
0
        public ActionResult DltCommentConfirmed(int id)
        {
            BlogComment blogComment = db.Comment.Find(id);
            BlogArticle blogArticle = db.Article.Find(blogComment.ArticleId);

            db.Comment.Remove(blogComment);
            db.SaveChanges();
            return(RedirectToAction("Details", new { Slug = blogArticle.Slug }));
        }
Example #30
0
 public UpdateBlogArticleModel MapToUpdate(BlogArticle entity)
 {
     return(new UpdateBlogArticleModel
     {
         Id = entity.Id,
         Title = entity.Title,
         Content = entity.Content,
     });
 }
        public override void Saved(HttpRequest request, string actualPath, string vpath)
        {
            #region arguments

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            #endregion

            // save through the base
            base.Saved(request, actualPath, vpath);

            // check if success saving the image.
            if (this.Success)
            {
                // associate image to the blog.
                string urlKey = request["urlkey"];
                if (!string.IsNullOrEmpty(urlKey))
                {
                    // load the blog article.
                    Article article = null;

                    if (ArticleStore.Instance.TryGetArticle(urlKey, PublishingStage.Draft, out article))
                    {
                        logger.Log(LogLevel.Debug, "Article's handler id - '{0}'", article.HandlerId);
                        if (BlogArticleHandler.CanHandle(article))
                        {
                            BlogArticle blogArticle = new BlogArticle(article);
                            if (blogArticle != null)
                            {
                                logger.Log(LogLevel.Info, "Photo '{0}' added to the article urlkey '{1}'.", vpath, urlKey);

                                //associate the image to articles gallery
                                blogArticle.AddImage(vpath);
                                blogArticle.Update();
                            }
                        }
                    }
                }
                else
                {
                    logger.Log(LogLevel.Warn, "Blog photo was uploaded successfully, however there was no article urlkey supplied.");

                    //delete the uploaded image
                    this.Success = false;
                    this.DeleteUploaded = true;
                }
            }
        }
Example #32
0
        public string AddImages(string urlKey, string[] images)
        {
            //make sure the user has access
            RatnaUser user = base.ValidatedUser();
            if (user == null)
            {
                return SendAccessDenied();
            }

            ServiceOutput output = new ServiceOutput();
            output.Success = false;

            if (!string.IsNullOrEmpty(urlKey))
            {
                try
                {

                    // photos can't be added to published articles
                    Article article = ArticleStore.Instance.GetArticle(urlKey, PublishingStage.Draft);
                    if (article != null)
                    {
                        if (BlogArticleHandler.CanHandle(article))
                        {
                            BlogArticle blogArticle = new BlogArticle(article);

                            foreach (string image in images)
                            {
                                blogArticle.AddImage(image);
                            }

                            blogArticle.Update();
                            output.Success = true;
                        }
                    }
                }
                catch (MessageException me)
                {
                    output.AddOutput(Constants.Json.Error, me.Message);
                }
                catch
                {
                    output.AddOutput(Constants.Json.Error, ResourceManager.GetLiteral("Admin.Articles.Edit.Update.Error"));
                }
            }

            return output.GetJson();
        }
Example #33
0
        public string RemoveImage(string urlKey, string images)
        {
            //make sure the user has access
            RatnaUser user = base.ValidatedUser();
            if (user == null)
            {
                return SendAccessDenied();
            }

            ServiceOutput output = new ServiceOutput();
            output.Success = false;

            if (!string.IsNullOrEmpty(urlKey))
            {
                try
                {

                    // photos can't be added to published articles
                    Article article = ArticleStore.Instance.GetArticle(urlKey, PublishingStage.Draft);
                    if (article != null)
                    {

                        //multiple images can be deleted at the same time.
                        if (images != null)
                        {
                            //check if there are multiple images to be deleted.
                            string[] tokens = images.Split(',');

                            if (tokens.Length > 0 && BlogArticleHandler.CanHandle(article))
                            {
                                BlogArticle blogArticle = new BlogArticle(article);
                                foreach (string token in tokens)
                                {
                                    if (!string.IsNullOrEmpty(token))
                                    {
                                        blogArticle.RemoveImage(token);
                                    }
                                }
                                blogArticle.Update();
                                output.Success = true;
                            }
                        }
                    }
                }
                catch (MessageException me)
                {
                    output.AddOutput(Constants.Json.Error, me.Message);
                }
                catch
                {
                    output.AddOutput(Constants.Json.Error, ResourceManager.GetLiteral("Admin.Articles.Edit.Update.Error"));
                }
            }

            return output.GetJson();
        }
Example #34
0
        public string Save(string urlKey, string title, string body)
        {
            //make sure the user has access
            RatnaUser user = base.ValidatedUser();
            if (user == null)
            {
                return SendAccessDenied();
            }

            ServiceOutput output = new ServiceOutput();
            output.Success = false;

            if (!string.IsNullOrEmpty(urlKey))
            {

                //make sure the url is relative and valid.
                if (!Uri.IsWellFormedUriString(urlKey, UriKind.Relative))
                {
                    // failed because URL is not valid.
                    output.AddOutput(Constants.Json.Error, ResourceManager.GetLiteral("Admin.Articles.Edit.Url.Validate.Error"));
                }
                else
                {
                    try
                    {
                        bool exists = ArticleStore.Instance.Exists(urlKey);

                        BlogArticle article = new BlogArticle();
                        article.UrlKey = urlKey;

                        // if the article already exists, read the article
                        // to sync with latest version
                        if (exists)
                        {
                            article.Read(PublishingStage.Draft);
                        }

                        article.Title = title;
                        article.Body = body;

                        if (!exists)
                        {
                            article.Owner = user;
                            article.Create();
                        }
                        else
                        {
                            article.Update();
                        }

                        output.Success = true;
                    }
                    catch (MessageException me)
                    {
                        logger.Log(LogLevel.Error, "Unable to save article. MessageException - {0}", me);
                        output.AddOutput(Constants.Json.Error, me.Message);
                    }
                    catch (Exception ex)
                    {
                        logger.Log(LogLevel.Error, "Unable to save article. Exception - {0}", ex);
                        output.AddOutput(Constants.Json.Error, ResourceManager.GetLiteral("Admin.Articles.Edit.Create.Error"));
                    }
                }
            }

            return output.GetJson();
        }
Example #35
0
		protected override void OnLoadComplete(EventArgs e)
		{
            if (AllSettings.Current.SpacePermissionSet.Can(My, SpacePermissionSet.Action.UseBlog) == false)
            {
                ShowError("您所在的用户组没有发表日志的权限");
            }

            if (My.Roles.IsInRole(Role.FullSiteBannedUsers))
                ShowError("您已经被整站屏蔽不能发表日志");

			if (_Request.IsClick("save"))
			{
				#region 页面提交时

				int id = _Request.Get<int>("id", 0);
				int? categoryID = _Request.Get<int>("category");

				string subject = _Request.Get("subject");
				string content = _Request.Get("content", Method.Post, string.Empty, false);
				string password = _Request.Get("password");
				string tagNames = _Request.Get("tag", Method.Post, string.Empty);
				string currentIP = _Request.IpAddress;

				bool enableComment = _Request.IsChecked("enablecomment", Method.Post, true);

				PrivacyType privacyType = _Request.Get<PrivacyType>("privacytype", PrivacyType.SelfVisible);

				using (ErrorScope es = new ErrorScope())
				{
					MessageDisplay md = CreateMessageDisplay(GetValidateCodeInputName("CreateBlogArticle"));

					if (CheckValidateCode("CreateBlogArticle", md))
					{
						bool succeed = false;

                        bool useHtml = _Request.Get("format") == "html";
                        bool useUbb = _Request.Get("format") == "ubb";

						if (IsEditMode)
						{
							succeed = BlogBO.Instance.UpdateBlogArticle(MyUserID, currentIP, id, subject, content, categoryID, tagNames.Split(','), enableComment, privacyType, password, useHtml, useUbb);
						}
						else
						{
							succeed = BlogBO.Instance.CreateBlogArticle(MyUserID, currentIP, subject, content, categoryID, tagNames.Split(','), enableComment, privacyType, password, useHtml, useUbb, out id);
						}

						if (succeed)
						{
							ValidateCodeManager.CreateValidateCodeActionRecode("CreateBlogArticle");

							BbsRouter.JumpTo("app/blog/index");
						}
						else
						{
							if (es.HasError)
							{
								es.CatchError<ErrorInfo>(delegate(ErrorInfo error)
								{
									md.AddError(error);
								});
							}
						}
					}
				}

				#endregion
            }
            else if (_Request.IsClick("addcategory"))
            {
                AddCategory();
            }
            

				#region 正常页面加载

				if (IsEditMode)
				{
					using (ErrorScope es = new ErrorScope())
					{
						int? articleID = _Request.Get<int>("id");

						if (articleID.HasValue)
						{
							m_Article = BlogBO.Instance.GetBlogArticleForEdit(MyUserID, articleID.Value);

							if (m_Article != null)
							{
								string[] tagNames = new string[m_Article.Tags.Count];

								for (int i = 0; i < tagNames.Length; i++ )
								{
									tagNames[i] = m_Article.Tags[i].Name;
								}

								m_ArticleTagList = StringUtil.Join(tagNames);

								m_CategoryList = BlogBO.Instance.GetUserBlogCategories(m_Article.UserID);
							}
						}

						if (m_Article == null)
						{
							ShowError("日志不存在");
						}

						if (es.HasUnCatchedError)
						{
							es.CatchError<ErrorInfo>(delegate(ErrorInfo error)
							{
								ShowError(error);
							});
						}

						base.OnLoadComplete(e);
					}

                    AddNavigationItem(FunctionName, BbsRouter.GetUrl("app/blog/index"));
                    AddNavigationItem("编辑日志");
				}
				else
				{
					m_Article = new BlogArticle();

					m_ArticleTagList = string.Empty;

					m_CategoryList = BlogBO.Instance.GetUserBlogCategories(MyUserID);

                    AddNavigationItem(FunctionName, BbsRouter.GetUrl("app/blog/index"));
                    AddNavigationItem("发表新日志");
				}


                m_ArticleList = BlogBO.Instance.GetUserBlogArticles(MyUserID, MyUserID, null, null, 1, 5);
				#endregion
        }
Example #36
0
        public virtual IList<Article> ReadInPath(string path, int start, int size, out int total)
        {
            #region arguments

            if (start < 0)
            {
                throw new ArgumentException("start");
            }

            if (size < 0)
            {
                throw new ArgumentException("size");
            }

            #endregion

            //default path
            if (string.IsNullOrEmpty(path))
            {
                path = "/";
            }

            IList<Article> articles = ArticleStore.Instance.ReadInPath(this, path, start, size, out total);

            // promote the articles that can be handled by this handler.
            IList<Article> promotedArticles = new List<Article>(articles.Count);

            foreach (Article article in articles)
            {
                Article pArticle = article;
                if (article.HandlerId == this.Id)
                {
                    pArticle = new BlogArticle(article);
                }
                promotedArticles.Add(pArticle);
            }

            return promotedArticles;
        }
Example #37
0
        public override BlogArticle GetBlogArticle(int articleID)
        {
            using (SqlQuery query = new SqlQuery())
            {
                query.CommandText = "bx_Blog_GetBlogArticle";

                query.CommandType = CommandType.StoredProcedure;

                query.CreateParameter<int>("@ArticleID", articleID, SqlDbType.Int);

                using (XSqlDataReader reader = query.ExecuteReader())
                {

                    TagCollection tags = new TagCollection(reader);

                    BlogArticleVisitorCollection visitors = null;

                    if (reader.NextResult())
                        visitors = new BlogArticleVisitorCollection(reader);

                    BlogArticle articles = null;

                    if (reader.NextResult() && reader.Read())
                    {
                        articles = new BlogArticle(reader);

                        articles.Tags = tags;
                        articles.LastVisitors = visitors;
                    }

                    return articles;
                }
            }
        }
Example #38
0
        public string SaveMetadata(string urlKey, string navigationtab, string tags, string description, string summary)
        {
            //make sure the user has access
            RatnaUser user = base.ValidatedUser();
            if (user == null)
            {
                return SendAccessDenied();
            }

            ServiceOutput output = new ServiceOutput();
            output.Success = false;

            if (!string.IsNullOrEmpty(urlKey))
            {
                try
                {
                    bool exists = ArticleStore.Instance.Exists(urlKey);

                    if (exists)
                    {

                        BlogArticle article = new BlogArticle();
                        article.UrlKey = urlKey;
                        article.Read(PublishingStage.Draft);
                        article.RemoveTags();

                        article.Description = description ?? string.Empty;
                        ((INavigationTag)article).Name = navigationtab ?? string.Empty; ;

                        if (!string.IsNullOrEmpty(tags))
                        {
                            article.AddTags(tags);
                        }

                        article.Summary = summary ?? string.Empty;
                        article.Update();

                        output.Success = true;
                    }
                }
                catch (MessageException me)
                {
                    logger.Log(LogLevel.Error, "Unable to save article metadata. MessageException - {0}", me);
                    output.AddOutput(Constants.Json.Error, me.Message);
                }
                catch (Exception ex)
                {
                    logger.Log(LogLevel.Error, "Unable to save article metadata. Exception - {0}", ex);
                    output.AddOutput(Constants.Json.Error, ResourceManager.GetLiteral("Admin.Articles.Edit.Create.Error"));
                }
            }

            return output.GetJson();
        }
Example #39
0
        public override Revertable2Collection<BlogArticle> GetBlogArticlesWithReverters(IEnumerable<int> articleIDs)
        {
            if (ValidateUtil.HasItems(articleIDs) == false)
                return null;

            Revertable2Collection<BlogArticle> articles = new Revertable2Collection<BlogArticle>();

            using (SqlQuery query = new SqlQuery())
            {
                query.CommandText = @"
SELECT 
	A.*,
	SubjectReverter = ISNULL(R.SubjectReverter, ''),
	ContentReverter = ISNULL(R.ContentReverter, '')
FROM 
	bx_BlogArticles A WITH(NOLOCK)
LEFT JOIN 
	bx_BlogArticleReverters R WITH(NOLOCK) ON R.ArticleID = A.ArticleID
WHERE 
	A.ArticleID IN (@ArticleIDs)";

                query.CreateInParameter<int>("@ArticleIDs", articleIDs);

                using (XSqlDataReader reader = query.ExecuteReader())
                {

                    while (reader.Read())
                    {
                        string subjectReverter = reader.Get<string>("SubjectReverter");
                        string contentReverter = reader.Get<string>("ContentReverter");

                        BlogArticle article = new BlogArticle(reader);

                        articles.Add(article, subjectReverter, contentReverter);
                    }
                }
            }

            return articles;
        }
Example #40
0
        protected bool CanSee(BlogArticle article)
        {
            if (IsSpace == false && SelectedMy)
                return true;

            if(article.UserID == MyUserID)
                return true;

            if (article.PrivacyType == PrivacyType.AllVisible)
                return true;

            if (IsSpace)
            {
                if (CanManageBlog)
                    return true;
            }

            if (article.PrivacyType == PrivacyType.FriendVisible)
            {
                if (SelectedFriend)
                    return true;
                else if (FriendBO.Instance.IsFriend(MyUserID, article.UserID))
                    return true;
            }
            else if (article.PrivacyType == PrivacyType.NeedPassword)
            {
                if (BlogBO.Instance.HasArticlePassword(My, article.ArticleID))
                    return true;
            }

            if (AllSettings.Current.BackendPermissions.Can(My, BackendPermissions.ActionWithTarget.Manage_Blog, article.UserID))
                return true;

            return false;
            
        }
Example #41
0
        public virtual IList<Article> Read(string query, long ownerId, int start, int size, out int total)
        {
            #region arguments

            if (start < 0)
            {
                throw new ArgumentException("start");
            }

            if (size < 0)
            {
                throw new ArgumentException("size");
            }

            #endregion

            IList<Article> articles = ArticleStore.Instance.Read(this, query, ownerId, start, size, out total);

            // promote the articles that can be handled by this handler.
            IList<Article> promotedArticles = new List<Article>(articles.Count);

            foreach (Article article in articles)
            {
                Article pArticle = article;
                if (article.HandlerId == this.Id)
                {
                    pArticle = new BlogArticle(article);
                }
                promotedArticles.Add(pArticle);
            }

            return promotedArticles;
        }
Example #42
0
 protected bool CanDeleteArticle(BlogArticle article)
 {
     return BlogBO.Instance.CheckBlogArticleDeletePermission(MyUserID, article);
 }
Example #43
0
        private void RenderForBlogArticle(BlogArticle article)
        {
            this.headdiv.Visible = false;

            if (article != null)
            {
                this.summary.Value = article.Summary;
                this.tags.Value = article.SerializedTags;
                this.navigationtab.Value = ((INavigationTag)article).Name;
                this.description.Value = article.Description;
            }
        }