示例#1
0
 public void BeginEdit()
 {
     beginblogName = BlogName;
     beginwebApi = WebAPI;
     beginblogInfo = BlogInfo;
     beginusername = Username;
     beginpassword = Password;
     beginlanguage = Language;
 }
示例#2
0
 /// <summary>
 /// Gets a collection of MetaTags for the given Blog.
 /// </summary>
 /// <returns></returns>
 public abstract IPagedCollection<MetaTag> GetMetaTagsForBlog(BlogInfo blog, int pageIndex, int pageSize);
示例#3
0
        public async Task <int> Delete(BlogInfo blogInfo)
        {
            var blog = mapper.Map <Blog>(blogInfo);

            return(await blogService.Delete(blog));
        }
        protected BlogInfo[] GetUsersBlogsInternal()
        {
            Uri         serviceUri = FeedServiceUrl;
            XmlDocument xmlDoc     = xmlRestRequestHelper.Get(ref serviceUri, RequestFilter);

            // Either the FeedServiceUrl points to a service document OR a feed.

            if (xmlDoc.SelectSingleNode("/app:service", _nsMgr) != null)
            {
                ArrayList blogInfos = new ArrayList();
                foreach (XmlElement coll in xmlDoc.SelectNodes("/app:service/app:workspace/app:collection", _nsMgr))
                {
                    bool promote = ShouldPromote(coll);

                    // does this collection accept entries?
                    XmlNodeList acceptNodes    = coll.SelectNodes("app:accept", _nsMgr);
                    bool        acceptsEntries = false;
                    if (acceptNodes.Count == 0)
                    {
                        acceptsEntries = true;
                    }
                    else
                    {
                        foreach (XmlElement acceptNode in acceptNodes)
                        {
                            if (AcceptsEntry(acceptNode.InnerText))
                            {
                                acceptsEntries = true;
                                break;
                            }
                        }
                    }

                    if (acceptsEntries)
                    {
                        string feedUrl = XmlHelper.GetUrl(coll, "@href", serviceUri);
                        if (feedUrl == null || feedUrl.Length == 0)
                        {
                            continue;
                        }

                        // form title
                        StringBuilder titleBuilder = new StringBuilder();
                        foreach (XmlElement titleContainerNode in new XmlElement[] { coll.ParentNode as XmlElement, coll })
                        {
                            Debug.Assert(titleContainerNode != null);
                            if (titleContainerNode != null)
                            {
                                XmlElement titleNode = titleContainerNode.SelectSingleNode("atom:title", _nsMgr) as XmlElement;
                                if (titleNode != null)
                                {
                                    string titlePart = _atomVer.TextNodeToPlaintext(titleNode);
                                    if (titlePart.Length != 0)
                                    {
                                        Res.LOCME("loc the separator between parts of the blog name");
                                        if (titleBuilder.Length != 0)
                                        {
                                            titleBuilder.Append(" - ");
                                        }
                                        titleBuilder.Append(titlePart);
                                    }
                                }
                            }
                        }

                        // get homepage URL
                        string      homepageUrl = "";
                        string      dummy       = "";
                        Uri         tempFeedUrl = new Uri(feedUrl);
                        XmlDocument feedDoc     = xmlRestRequestHelper.Get(ref tempFeedUrl, RequestFilter);
                        ParseFeedDoc(feedDoc, tempFeedUrl, false, ref homepageUrl, ref dummy);

                        // TODO: Sniff out the homepage URL
                        BlogInfo blogInfo = new BlogInfo(feedUrl, titleBuilder.ToString().Trim(), homepageUrl);
                        if (promote)
                        {
                            blogInfos.Insert(0, blogInfo);
                        }
                        else
                        {
                            blogInfos.Add(blogInfo);
                        }
                    }
                }

                return((BlogInfo[])blogInfos.ToArray(typeof(BlogInfo)));
            }
            else
            {
                string title       = string.Empty;
                string homepageUrl = string.Empty;

                ParseFeedDoc(xmlDoc, serviceUri, true, ref homepageUrl, ref title);

                return(new BlogInfo[] { new BlogInfo(UrlHelper.SafeToAbsoluteUri(FeedServiceUrl), title, homepageUrl) });
            }
        }
        public static string ForwardRealization(BlogUser userinfo, string tag, string type, string url, string siteUrl, bool isshowhome, bool isshowmyhome, bool isBJ = false)
        {
            if (userinfo != null)
            {
                int typeint = -1;
                int.TryParse(type, out typeint);
                var tags = tag.Split(',');

                var jp        = new JumonyParser();
                var html      = jp.LoadDocument(url);
                var titlehtml = html.Find(".postTitle a").FirstOrDefault().InnerHtml();
                if (!isBJ)
                {
                    titlehtml = "【转】" + titlehtml;
                }
                else
                {
                    titlehtml = "《" + titlehtml + "》";
                }
                var bodyhtml = html.Find("#cnblogs_post_body").FirstOrDefault().InnerHtml();
                bodyhtml += "</br><div class='div_zf'>==================================<a  href='" + url + "' target='_blank'>原文链接</a>==================================</div>";

                var mtag = BLL.Common.GetDataHelper.GetAllTag().Where(t => tags.Contains(t.TagName)).ToList();

                var blogtagid = new List <int>();
                for (int i = 0; i < tags.Length; i++)
                {
                    blogtagid.Add(GetTagId(tags[i], userinfo.Id));
                }
                //&& t.UsersId == userinfo.Id         理论是不用 加用户id 筛选
                var myBlogTags  = new BLL.BaseBLL <BlogTag>().GetList(t => blogtagid.Contains(t.Id), isAsNoTracking: false).ToList();
                var myBlogTypes = new BLL.BaseBLL <BlogType>().GetList(t => t.Id == typeint, isAsNoTracking: false).ToList();

                object obj  = null;
                string call = string.Empty;
                BLL.BaseBLL <BlogInfo> blogbll = new BaseBLL <BlogInfo>();

                var blogtemp = blogbll.GetList(t => t.User.Id == userinfo.Id).OrderByDescending(t => t.Id).FirstOrDefault();
                if (blogtemp != null && blogtemp.Title == titlehtml)
                {
                    obj  = new { s = "no", m = "已存在相同标题博客文章~", u = siteUrl };
                    call = obj.ToJson();
                    //Response.Write(call);
                    return(call);
                }

                var blogmode = new BlogInfo()
                {
                    User           = userinfo,
                    Title          = titlehtml,
                    Types          = myBlogTypes,
                    Tags           = myBlogTags,
                    Content        = bodyhtml,
                    CreationTime   = DateTime.Now,
                    BlogCreateTime = DateTime.Now,
                    BlogUpTime     = DateTime.Now,
                    IsShowMyHome   = isshowmyhome,
                    IsShowHome     = isshowhome
                };

                blogbll.Insert(blogmode);

                if (blogbll.save() > 0)
                {
                    obj  = new { s = "ok", m = "发布成功", u = siteUrl + "/" + userinfo.UserName + "/" + blogmode.Id + ".html" };
                    call = obj.ToJson();
                    //Response.Write(call);
                    return(call);
                }
                obj  = new { s = "no", m = "发布失败", u = siteUrl + "/" + userinfo.UserName + "/" + blogmode.Id + ".html" };
                call = obj.ToJson();
                //Response.Write(call);
                return(call);
            }
            else
            {
                var obj  = new { s = "no", m = "发布失败", u = siteUrl + "/" };
                var call = obj.ToJson();
                //Response.Write(call);
                return(call);
            }
        }
示例#6
0
 /// <summary>
 /// 保存添加数据 Add(BlogInfo entity)
 /// </summary>
 /// <param name="entity">实体类(BlogInfo)</param>
 ///<returns>返回新增的ID</returns>
 public void Add(BlogInfo entity)
 {
     _blog.Add(entity);
 }
示例#7
0
文件: Config.cs 项目: ayende/Subtext
        /// <summary>
        /// Updates the database with the configuration data within 
        /// the specified <see cref="BlogInfo"/> instance.
        /// </summary>
        /// <param name="info">Config.</param>
        /// <returns></returns>
        public static void UpdateConfigData(BlogInfo info)
        {
            //Check for duplicate
            BlogInfo potentialDuplicate = GetBlogInfo(info.Host, info.Subfolder, true);
            if (potentialDuplicate != null && !potentialDuplicate.Equals(info))
            {
                //we found a duplicate!
                throw new BlogDuplicationException(potentialDuplicate);
            }

            //Check to see if we're going to end up hiding another blog.
            BlogInfo potentialHidden = GetBlogInfo(info.Host, string.Empty, true);
            if (potentialHidden != null && !potentialHidden.Equals(info) && potentialHidden.IsActive)
            {
                //We found a blog that would be hidden by this one.
                throw new BlogHiddenException(potentialHidden);
            }

            string subfolderName = info.Subfolder == null ? string.Empty : UrlFormats.StripSurroundingSlashes(info.Subfolder);

            if (subfolderName.Length == 0)
            {
                //Check to see if this blog requires a Subfolder value
                //This would occur if another blog has the same host already.
                IPagedCollection<BlogInfo> blogsWithHost = BlogInfo.GetBlogsByHost(info.Host, 0, 1, ConfigurationFlags.IsActive);
                if(blogsWithHost.Count > 0)
                {
                    if (blogsWithHost.Count > 1 || !blogsWithHost[0].Equals(info))
                    {
                        throw new BlogRequiresSubfolderException(info.Host, blogsWithHost.Count);
                    }
                }
            }
            else
            {
                if (!IsValidSubfolderName(subfolderName))
                {
                    throw new InvalidSubfolderNameException(subfolderName);
                }
            }

            info.IsPasswordHashed = Settings.UseHashedPasswords;
            info.AllowServiceAccess = Settings.AllowServiceAccess;

            ObjectProvider.Instance().UpdateBlog(info);
        }
示例#8
0
 /// <summary>
 /// Creates a new <see cref="BlogHiddenException"/> instance.
 /// </summary>
 /// <param name="hidden">Hidden.</param>
 public BlogHiddenException(BlogInfo hidden)
     : this(hidden, NullValue.NullInt32)
 {
 }
示例#9
0
 public async Task CreateOrUpdateBlog(BlogInfo blogInfo)
 {
     await blogApplication.CreateOrUpdateBlog(blogInfo);
 }
示例#10
0
        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="uname"></param>
        /// <param name="useTime"></param>
        /// <returns></returns>
        public static string DowanloadBlog(Dictionary <BlogType, List <BlogInfo> > dic, string uname, out long useTime)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            int countFlag = 0;

            for (int i = 0; i < dic.Keys.Count; i++)
            {
                var blogType = dic.Keys.ElementAt(i);
                var blogList = dic[blogType];
                var dicPath  = AppDomain.CurrentDomain.BaseDirectory + "BlogFiles\\" + uname + "\\" + blogType.BlogTypeName;
                Console.WriteLine("<<开始处理分类【{0}】<<", blogType.BlogTypeName);
                FileHelper.CreatePath(dicPath);
                var blogModel = new BlogInfo();
                for (int j = 0; j < blogList.Count; j++)
                {
                    countFlag++;
                    try
                    {
                        Console.WriteLine("~~~~开始处理文章{0}【{1}】~~~~", countFlag, blogModel.BlogTitle);
                        blogModel = blogList[j];
                        var          filePath = dicPath + "\\" + FileHelper.FilterInvalidChar(blogModel.BlogTitle, "_") + ".html";
                        HtmlDocument doc      = new HtmlDocument();
                        doc.DocumentNode.InnerHtml = blogModel.BlogContent;

                        //处理图片
                        Console.WriteLine("~~开始处理图片");
                        var imgPath = dicPath + "\\Content\\images";
                        FileHelper.CreatePath(imgPath);
                        SaveImage(doc, imgPath);
                        Console.WriteLine("~~处理图片完成");

                        //去掉a标签
                        var aNodes = doc.DocumentNode.SelectNodes("//a");
                        if (aNodes != null && aNodes.Count > 0)
                        {
                            for (int a = 0; a < aNodes.Count; a++)
                            {
                                if (aNodes[a].Attributes["href"] != null && aNodes[a].Attributes["href"].Value != "#")
                                {
                                    aNodes[a].Attributes["href"].Value = "javascript:void()";
                                }
                            }
                        }


                        //将随笔转换为iBlog Post模型
                        var labels = doc.DocumentNode.InnerText.GetArticleKeywordJson();
                        var date   = DateTime.Now;
                        DateTime.TryParse(blogModel.BlogPostTime, out date);
                        var cate = "";
                        if (dictCates.ContainsKey(blogModel.BlogTypeName))
                        {
                            cate = dictCates[blogModel.BlogTypeName];
                        }

                        var post = new Post
                        {
                            IsActive      = true,
                            Alias         = RandomStringGenerator.Instance.Generate(6),
                            CategoryAlias = cate,
                            Content       = doc.DocumentNode.InnerHtml,
                            Url           = blogModel.BlogUrl,
                            CreateTime    = date,
                            ModifyTime    = date,
                            Source        = "0",
                            Title         = blogModel.BlogTitle,
                            Summary       = blogModel.BlogTitle,
                            Labels        = labels
                        };

                        AddArticle(post);

                        doc.DocumentNode.InnerHtml = "<div id='div_head'>" + uname + " " + blogType.BlogTypeName + "</div><div id='div_title'>" + blogModel.BlogTitle + "<div><div id='div_body'>" + doc.DocumentNode.InnerHtml + "</div>";
                        doc.Save(filePath, Encoding.UTF8);


                        Console.WriteLine("~~~~处理文章{0}【{1}】完毕~~~~", countFlag, blogModel.BlogTitle);
                    }
                    catch (Exception ex)
                    {
                        string errorMsg = DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + "\r\n" + "url=" + blogModel.BlogUrl + "\r\n" + "title=" + blogModel.BlogTitle + "\r\n" + "errorMsg=" + ex.Message + "\r\n" + "stackTrace=" + ex.StackTrace + "\r\n\r\n\r\n";
                        Console.WriteLine("error>>处理文章【{0}】出现错误,开始记录错误信息~~", blogModel.BlogTitle);
                        FileHelper.SaveTxtFile(dicPath, "errorLog.txt", errorMsg, false);
                        Console.WriteLine("error>>处理文章【{0}】出现错误,记录错误信息完成~~", blogModel.BlogTitle);
                    }
                }
                Console.WriteLine("<<处理分类【{0}】完成<<", blogType.BlogTypeName);
            }
            sw.Start();
            useTime = sw.ElapsedMilliseconds;
            return(AppDomain.CurrentDomain.BaseDirectory + "BlogFiles\\" + uname);
        }
示例#11
0
 public abstract IDataReader GetMetaTagsForBlog(BlogInfo blog, int pageIndex, int pageSize);
示例#12
0
 public void LoadTitleEntity(DataRow row, BlogInfo blogInfo)
 {
     blogInfo.BlogId      = Convert.ToInt64(row["BlogId"]);
     blogInfo.Title       = row["Title"] != DBNull.Value ? row["Title"].ToString() : string.Empty;
     blogInfo.CreatedTime = Convert.ToDateTime(row["CreatedTime"]);
 }
示例#13
0
 /// <summary>
 /// Creates a new <see cref="BlogDuplicationException"/> instance.
 /// </summary>
 /// <param name="duplicate">Duplicate.</param>
 /// <param name="blogId">Blog id of the blog we were updating.  If this is .</param>
 public BlogDuplicationException(BlogInfo duplicate, int blogId)
     : base()
 {
     _duplicateBlog = duplicate;
     _blogId = blogId;
 }
示例#14
0
 /// <summary>
 /// Creates a new <see cref="BlogDuplicationException"/> instance.
 /// </summary>
 /// <param name="duplicate">Duplicate.</param>
 public BlogDuplicationException(BlogInfo duplicate)
     : this(duplicate, NullValue.NullInt32)
 {
 }
示例#15
0
 public void Update_Blog(BlogInfo blog)
 {
     _blogRepo.Update_Blog(blog);
 }
示例#16
0
 /// <summary>
 /// Updates the specified blog configuration.
 /// </summary>
 /// <param name="info">Config.</param>
 /// <returns></returns>
 public abstract bool UpdateBlog(BlogInfo info);
示例#17
0
 BlogInfo[] IBlogger.blogger_getUsersBlogs(string appKey, string username, string password)
 {
     AssertCredentials(username, password);
     BlogInfo b = new BlogInfo();
     b.blogid = "1";
     b.blogName = "imagineClub";
     b.url = GetBlogUrl();
     return new BlogInfo[] { b };
 }
示例#18
0
 public async Task <int> DeleteBlog(BlogInfo blog)
 {
     return(await blogApplication.Delete(blog));
 }
示例#19
0
 public int Insert_Blog(BlogInfo blog)
 {
     return(_blogRepo.Insert_Blog(blog));
 }
示例#20
0
 public async Task <IActionResult> AddBlog([FromBody] BlogInfo blogInfo)
 {
     return(Ok(await _blogRepository.AddBlog(blogInfo)));
 }
        public void CopyFrom(TemporaryBlogSettings sourceSettings)
        {
            // simple members
            _id                   = sourceSettings._id;
            _switchToWeblog       = sourceSettings._switchToWeblog;
            _isNewWeblog          = sourceSettings._isNewWeblog;
            _savePassword         = sourceSettings._savePassword;
            _isSpacesBlog         = sourceSettings._isSpacesBlog;
            _isSharePointBlog     = sourceSettings._isSharePointBlog;
            _isGoogleBloggerBlog  = sourceSettings._isGoogleBloggerBlog;
            _isStaticSiteBlog     = sourceSettings._isStaticSiteBlog;
            _hostBlogId           = sourceSettings._hostBlogId;
            _blogName             = sourceSettings._blogName;
            _homePageUrl          = sourceSettings._homePageUrl;
            _manifestDownloadInfo = sourceSettings._manifestDownloadInfo;
            _providerId           = sourceSettings._providerId;
            _serviceName          = sourceSettings._serviceName;
            _clientType           = sourceSettings._clientType;
            _postApiUrl           = sourceSettings._postApiUrl;
            _lastPublishFailed    = sourceSettings._lastPublishFailed;
            _fileUploadSupport    = sourceSettings._fileUploadSupport;
            _instrumentationOptIn = sourceSettings._instrumentationOptIn;

            if (sourceSettings._availableImageEndpoints == null)
            {
                _availableImageEndpoints = null;
            }
            else
            {
                // Good thing BlogInfo is immutable!
                _availableImageEndpoints = (BlogInfo[])sourceSettings._availableImageEndpoints.Clone();
            }

            // credentials
            BlogCredentialsHelper.Copy(sourceSettings._credentials, _credentials);

            // template files
            _templateFiles = new BlogEditingTemplateFile[sourceSettings._templateFiles.Length];
            for (int i = 0; i < sourceSettings._templateFiles.Length; i++)
            {
                BlogEditingTemplateFile sourceFile = sourceSettings._templateFiles[i];
                _templateFiles[i] = new BlogEditingTemplateFile(sourceFile.TemplateType, sourceFile.TemplateFile);
            }

            // option overrides
            if (sourceSettings._optionOverrides != null)
            {
                _optionOverrides.Clear();
                foreach (DictionaryEntry entry in sourceSettings._optionOverrides)
                {
                    _optionOverrides.Add(entry.Key, entry.Value);
                }
            }

            // user option overrides
            if (sourceSettings._userOptionOverrides != null)
            {
                _userOptionOverrides.Clear();
                foreach (DictionaryEntry entry in sourceSettings._userOptionOverrides)
                {
                    _userOptionOverrides.Add(entry.Key, entry.Value);
                }
            }

            // homepage overrides
            if (sourceSettings._homepageOptionOverrides != null)
            {
                _homepageOptionOverrides.Clear();
                foreach (DictionaryEntry entry in sourceSettings._homepageOptionOverrides)
                {
                    _homepageOptionOverrides.Add(entry.Key, entry.Value);
                }
            }

            // categories
            if (sourceSettings._categories != null)
            {
                _categories = new BlogPostCategory[sourceSettings._categories.Length];
                for (int i = 0; i < sourceSettings._categories.Length; i++)
                {
                    BlogPostCategory sourceCategory = sourceSettings._categories[i];
                    _categories[i] = sourceCategory.Clone() as BlogPostCategory;
                }
            }
            else
            {
                _categories = null;
            }

            if (sourceSettings._keywords != null)
            {
                _keywords = new BlogPostKeyword[sourceSettings._keywords.Length];
                for (int i = 0; i < sourceSettings._keywords.Length; i++)
                {
                    BlogPostKeyword sourceKeyword = sourceSettings._keywords[i];
                    _keywords[i] = sourceKeyword.Clone() as BlogPostKeyword;
                }
            }
            else
            {
                _keywords = null;
            }

            // authors and pages
            _authors = sourceSettings._authors.Clone() as AuthorInfo[];
            _pages   = sourceSettings._pages.Clone() as PageInfo[];

            // buttons
            if (sourceSettings._buttonDescriptions != null)
            {
                _buttonDescriptions = new BlogProviderButtonDescription[sourceSettings._buttonDescriptions.Length];
                for (int i = 0; i < sourceSettings._buttonDescriptions.Length; i++)
                {
                    _buttonDescriptions[i] = sourceSettings._buttonDescriptions[i].Clone() as BlogProviderButtonDescription;
                }
            }
            else
            {
                _buttonDescriptions = null;
            }

            // favicon
            _favIcon = sourceSettings._favIcon;

            // images
            _image          = sourceSettings._image;
            _watermarkImage = sourceSettings._watermarkImage;

            // host blogs
            _hostBlogs = new BlogInfo[sourceSettings._hostBlogs.Length];
            for (int i = 0; i < sourceSettings._hostBlogs.Length; i++)
            {
                BlogInfo sourceBlog = sourceSettings._hostBlogs[i];
                _hostBlogs[i] = new BlogInfo(sourceBlog.Id, sourceBlog.Name, sourceBlog.HomepageUrl);
            }

            // file upload settings
            _fileUploadSettings = sourceSettings._fileUploadSettings.Clone() as TemporaryFileUploadSettings;

            _pluginSettings = new SettingsPersisterHelper(new MemorySettingsPersister());
            _pluginSettings.CopyFrom(sourceSettings._pluginSettings, true, true);
        }
        private bool AttemptRsdBasedDetection(IProgressHost progressHost, RsdServiceDescription rsdServiceDescription)
        {
            // always return alse for null description
            if (rsdServiceDescription == null)
            {
                return(false);
            }

            string      providerId  = String.Empty;
            BlogAccount blogAccount = null;

            // check for a match on rsd engine link
            foreach (IBlogProvider provider in BlogProviderManager.Providers)
            {
                blogAccount = provider.DetectAccountFromRsdHomepageLink(rsdServiceDescription);
                if (blogAccount != null)
                {
                    providerId = provider.Id;
                    break;
                }
            }

            // if none found on engine link, match on engine name
            if (blogAccount == null)
            {
                foreach (IBlogProvider provider in BlogProviderManager.Providers)
                {
                    blogAccount = provider.DetectAccountFromRsdEngineName(rsdServiceDescription);
                    if (blogAccount != null)
                    {
                        providerId = provider.Id;
                        break;
                    }
                }
            }

            // No provider associated with the RSD file, try to gin one up (will only
            // work if the RSD file contains an API for one of our supported client types)
            if (blogAccount == null)
            {
                // try to create one from RSD
                blogAccount = BlogAccountFromRsdServiceDescription.Create(rsdServiceDescription);
            }

            // if we have an rsd-detected weblog
            if (blogAccount != null)
            {
                // confirm that the credentials are OK
                UpdateProgress(progressHost, 65, Res.Get(StringId.ProgressVerifyingInterface));
                BlogAccountDetector blogAccountDetector = new BlogAccountDetector(
                    blogAccount.ClientType, blogAccount.PostApiUrl, _credentials);

                if (blogAccountDetector.ValidateService())
                {
                    // copy basic account info
                    _providerId  = providerId;
                    _serviceName = blogAccount.ServiceName;
                    _clientType  = blogAccount.ClientType;
                    _hostBlogId  = blogAccount.BlogId;
                    _postApiUrl  = blogAccount.PostApiUrl;

                    // see if we can improve on the blog name guess we already
                    // have from the <title> element of the homepage
                    BlogInfo blogInfo = blogAccountDetector.DetectAccount(_homepageUrl, _hostBlogId);
                    if (blogInfo != null)
                    {
                        _blogName = blogInfo.Name;
                    }
                }
                else
                {
                    // report user-authorization error
                    ReportErrorAndFail(blogAccountDetector.ErrorMessageType, blogAccountDetector.ErrorMessageParams);
                }

                // success!
                return(true);
            }
            else
            {
                // couldn't do it
                return(false);
            }
        }
示例#23
0
 /// <summary>
 /// 更新数据 Update(BlogInfo entity)
 /// </summary>
 /// <param name="entity">实体类(BlogInfo)</param>
 ///<returns>true:保存成功; false:保存失败</returns>
 public bool Update(BlogInfo entity)
 {
     return(_blog.Update(entity));
 }
示例#24
0
        public void SetBlog(UserBlog userBlog, User userInfo)
        {
            BlogInfo blogInfo = blogService.GetBlogInfo(userBlog, userInfo);

            ViewBag.blogInfo = blogInfo;
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        currentUser = CMSContext.CurrentUser;
        if (currentUser == null)
        {
            return;
        }

        // No cms.blog doc. type
        if (DataClassInfoProvider.GetDataClass("cms.blog") == null)
        {
            RedirectToInformation(GetString("blog.noblogdoctype"));
        }

        // Check if user is authorized to manage
        isAuthorized = currentUser.IsAuthorizedPerResource("CMS.Blog", "Manage") || (currentUser.IsAuthorizedPerClassName("cms.blog", "Manage", CMSContext.CurrentSiteName) &&
                                                                                     currentUser.IsAuthorizedPerClassName("cms.blogpost", "Manage", CMSContext.CurrentSiteName));

        // Register grid events
        gridBlogs.OnExternalDataBound += gridBlogs_OnExternalDataBound;
        gridBlogs.OnDataReload += gridBlogs_OnDataReload;
        gridBlogs.ShowActionsMenu = true;
        gridBlogs.Columns = "BlogID, ClassName, BlogName, NodeID, DocumentCulture, NodeOwner, BlogModerators";

        // Get all possible columns to retrieve
        IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree");
        DocumentInfo di = new DocumentInfo();
        BlogInfo bi = new BlogInfo();
        gridBlogs.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(bi.ColumnNames), SqlHelperClass.MergeColumns(di.ColumnNames)), SqlHelperClass.MergeColumns(nodeClass.ColumnNames));

        // Get ClassID of the 'cms.blogpost' class
        DataClassInfo dci = DataClassInfoProvider.GetDataClass("cms.blogpost");
        string classId = "";
        string script = "";

        if (dci != null)
        {
            classId = dci.ClassID.ToString();
        }

        // Get script to redirect to new blog post page
        script += "function NewPost(parentId, culture) { \n";
        script += "     if (parentId != 0) { \n";
        script += "         parent.parent.parent.location.href = \"" + ResolveUrl("~/CMSDesk/default.aspx") + "?section=content&action=new&nodeid=\" + parentId + \"&classid=" + classId + "&culture=\" + culture;";
        script += "}} \n";

        // Generate javascript code
        ltlScript.Text = ScriptHelper.GetScript(script);
    }
示例#26
0
        public MetaWeblog.BlogInfo[] getUsersBlogs(string appKey, string username,string password)
        {
            if(ValidateUser(username,password))
            {
                BlogInfo[] al = new BlogInfo[1];

                BlogInfo bi = new BlogInfo();
                bi.blogid = "root_blog";
                bi.blogName = SiteSettings.Get().Title;
                bi.url = new Macros().FullUrl("~/");
                al[0] = bi;

                return al;
            }

            throw new XmlRpcFaultException(0,"User does not exist");
        }
示例#27
0
        /// <summary>
        /// Writes the RSD for the specified blog into the XmlWriter.
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="blog"></param>
        public void WriteRsd(XmlWriter writer, BlogInfo blog)
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("rsd", "http://archipelago.phrasewise.com/rsd");
            writer.WriteAttributeString("version", "1.0");
            writer.WriteStartElement("service");
            writer.WriteElementString("engineName", "Subtext");
            writer.WriteElementString("engineLink", "http://subtextproject.com/");
            writer.WriteElementString("homePageLink", blog.HomeFullyQualifiedUrl.ToString());

            writer.WriteStartElement("apis");

            //When we have more than one API, we'll list them here.
            writer.WriteStartElement("api");
            writer.WriteAttributeString("name", "MetaWeblog");
            writer.WriteAttributeString("preferred", "true");
            writer.WriteAttributeString("apiLink", blog.RootUrl + "services/metablogapi.aspx");
            writer.WriteAttributeString("blogID", Config.CurrentBlog.Id.ToString(CultureInfo.InvariantCulture));
            writer.WriteEndElement(); // </api>

            writer.WriteEndElement(); // </apis>

            writer.WriteEndElement(); // </service>
            writer.WriteEndElement(); // </rsd>
            writer.WriteEndDocument();
            writer.Flush();
        }
示例#28
0
        /// <summary>
        /// 根据用户导入cnblog数据
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public string Import(string userName, string iszf, string isshowhome, string isshowmyhome)
        {
            userName = userName.Trim();
            int blosNumber           = 0;
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string url = "http://www.cnblogs.com/" + userName + @"/mvc/blog/sidecolumn.aspx";

            HtmlAgilityPack.HtmlWeb      htmlweb  = new HtmlAgilityPack.HtmlWeb();
            HtmlAgilityPack.HtmlDocument document = new HtmlDocument();
            var    docment = htmlweb.Load(url);
            string userid  = GetCnblogUserId(userName);
            var    liS     = docment.DocumentNode.SelectNodes("//*[@id='sidebar_categories']/div[1]/ul/li");

            foreach (var item in liS)
            {
                var tXPath   = item.XPath;
                var href     = item.SelectSingleNode(tXPath + "/a").Attributes["href"].Value;
                var blogtype = htmlweb.Load(href);
                //var entrylistItem = blogtype.DocumentNode.SelectNodes("//*[@id='mainContent']/div/div[2]/div[@class='entrylistItem']");
                var entrylistItem = blogtype.DocumentNode.SelectNodes("//div[@class='entrylistItem']");
                if (null == entrylistItem)                                                                    //做兼容
                {
                    entrylistItem = blogtype.DocumentNode.SelectNodes("//div[@class='post post-list-item']"); //
                }
                if (null == entrylistItem)
                {
                    continue;
                }
                foreach (var typeitem in entrylistItem)
                {
                    var typeitemXPath   = typeitem.XPath;
                    var typeitemhrefObj = typeitem.SelectSingleNode(typeitemXPath + "/div/a");
                    if (null == typeitemhrefObj) //做兼容
                    {
                        typeitemhrefObj = typeitem.SelectSingleNode(typeitemXPath + "/h2/a");
                    }
                    var typeitemhref = typeitemhrefObj.Attributes["href"].Value;
                    if (IsAreBlog(typeitemhref))
                    {
                        continue;//说明这篇文章已经备份过了的
                    }
                    var bloghtml       = htmlweb.Load(typeitemhref);
                    var blogcontextobj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cnblogs_post_body']");//.InnerHtml;
                    if (blogcontextobj == null)
                    {
                        continue;                        //有可能是加密文章
                    }
                    var blogcontext = blogcontextobj.InnerHtml;

                    var blogNameObj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='Header1_HeaderTitle']");
                    if (null == blogNameObj)
                    {
                        blogNameObj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='lnkBlogTitle']");
                    }
                    try
                    {
                        blogName = blogNameObj.InnerText;
                    }
                    catch (Exception)
                    { throw; }

                    var blogtitle      = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']").InnerText;
                    var blogurl        = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']").Attributes["href"].Value;
                    var blogtypetagurl = "http://www.cnblogs.com/mvc/blog/CategoriesTags.aspx?blogApp=" + userName + "&blogId=" + userid + "&postId=" +
                                         typeitemhref.Substring(typeitemhref.LastIndexOf('/') + 1, typeitemhref.LastIndexOf('.') - typeitemhref.LastIndexOf('/') - 1);
                    var blogtag = Blogs.Common.Helper.MyHtmlHelper.GetRequest(blogtypetagurl);
                    var jsonobj = jss.Deserialize <Dictionary <string, string> >(blogtag);
                    if (null == jsonobj)
                    {
                        continue;//如果没有 则返回  (这里只能去 数字.html  不能取那种自定义的url)
                    }
                    var tagSplit  = jsonobj["Tags"].Split(',');
                    var blogtagid = new List <int>();
                    for (int i = 0; i < tagSplit.Length; i++)
                    {
                        if (tagSplit[i].Length >= 1 && tagSplit[i].LastIndexOf('<') >= 1)
                        {
                            var blogtagname = tagSplit[i].Substring(tagSplit[i].IndexOf('>') + 1, tagSplit[i].LastIndexOf('<') - tagSplit[i].IndexOf('>') - 1);
                            blogtagid.Add(this.GetTagId(blogtagname, userName));
                        }
                    }
                    var categoriesSplit = jsonobj["Categories"].Split(',');
                    var blogtypeid      = new List <int>();
                    for (int i = 0; i < categoriesSplit.Length; i++)
                    {
                        if (categoriesSplit[i].Length >= 1 && categoriesSplit[i].LastIndexOf('<') >= 1)
                        {
                            var blogtypename = categoriesSplit[i].Substring(categoriesSplit[i].IndexOf('>') + 1, categoriesSplit[i].LastIndexOf('<') - categoriesSplit[i].IndexOf('>') - 1);
                            blogtypeid.Add(this.GetTypeId(blogtypename, userName));
                        }
                    }
                    var blogtimeobj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='post-date']");
                    var blogtime    = "";
                    if (null != blogtimeobj)
                    {
                        blogtime = blogtimeobj.InnerText;
                    }

                    DateTime?createtime    = null;
                    var      Outcreatetime = DateTime.Now;
                    if (DateTime.TryParse(blogtime, out Outcreatetime))
                    {
                        createtime = Outcreatetime;
                    }
                    BLL.BaseBLL <BlogInfo> blog = new BaseBLL <BlogInfo>();
                    var myBlogTags  = new BLL.BaseBLL <BlogTag>().GetList(t => blogtagid.Contains(t.Id), isAsNoTracking: false).ToList();   //.ToList();
                    var myBlogTypes = new BLL.BaseBLL <BlogType>().GetList(t => blogtypeid.Contains(t.Id), isAsNoTracking: false).ToList(); //.ToList();

                    var tmepUserid = GetUserId(userName);
                    var user       = new BLL.BaseBLL <BlogUser>().GetList(t => t.Id == tmepUserid, isAsNoTracking: false).FirstOrDefault();

                    try
                    {
                        var modelMyBlogs = new BlogInfo()
                        {
                            Content        = blogcontext,
                            BlogCreateTime = createtime,
                            Title          = blogtitle,
                            Url            = blogurl,
                            IsDelte        = false,
                            Tags           = myBlogTags,
                            Types          = myBlogTypes,
                            User           = user,// new BlogUser { Id = tmepUserid, IsLock = false, BlogUserInfo = new BlogUserInfo() },
                            ForUrl         = blogurl,
                            IsForwarding   = iszf == "true",
                            IsShowMyHome   = isshowmyhome == "true",
                            IsShowHome     = isshowhome == "true"
                        };
                        blog.Insert(modelMyBlogs);
                        //blog.save(false);
                        BLL.BaseBLL <BlogInfo> .StaticSave();

                        var newtag = string.Empty;
                        try
                        {
                            modelMyBlogs.Tags.Where(t => true).ToList().ForEach(t => newtag += t.TagName + " ");
                            var          newblogurl = "/" + modelMyBlogs.User.UserName + "/" + modelMyBlogs.Id + ".html";
                            SearchResult search     = new SearchResult()
                            {
                                flag          = modelMyBlogs.User.Id,
                                id            = modelMyBlogs.Id,
                                title         = blogtitle,
                                clickQuantity = 0,
                                blogTag       = newtag,
                                content       = getText(blogcontext, document),
                                url           = newblogurl
                            };

                            SafetyWriteHelper <SearchResult> .logWrite(search, PanGuLuceneHelper.instance.CreateIndex);
                        }
                        catch (Exception)
                        {
                            throw;
                        }

                        var postid = blogurl.Substring(blogurl.LastIndexOf('/') + 1);
                        postid = postid.Substring(0, postid.LastIndexOf('.'));
                        testJumonyParser(modelMyBlogs.Id, postid, userName);

                        blosNumber++;
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }
            }
            if (blosNumber > 0)
            {
                Blogs.BLL.Common.GetDataHelper.GetAllTag();
                //Blogs.BLL.Common.CacheData.GetAllType(true);
                //Blogs.BLL.Common.CacheData.GetAllUserInfo(true);
                return("成功导入" + blosNumber + "篇Blog");
            }
            return("ok");
        }
示例#29
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check the current user
        currentUser = CMSContext.CurrentUser;
        if (currentUser == null)
        {
            return;
        }

        // Check 'Read' permission
        if (currentUser.IsAuthorizedPerResource("cms.blog", "Read"))
        {
            readBlogs = true;
        }

        if (!RequestHelper.IsPostBack())
        {
            this.drpBlogs.Items.Add(new ListItem(GetString("general.selectall"), "##ALL##"));
            this.drpBlogs.Items.Add(new ListItem(GetString("blog.selectmyblogs"), "##MYBLOGS##"));
        }

        // No cms.blog doc. type
        if (DataClassInfoProvider.GetDataClass("cms.blog") == null)
        {
            RedirectToInformation(GetString("blog.noblogdoctype"));
        }

        this.CurrentMaster.DisplaySiteSelectorPanel = true;

        gridBlogs.OnDataReload += gridBlogs_OnDataReload;
        gridBlogs.ZeroRowsText = GetString("general.nodatafound");
        gridBlogs.ShowActionsMenu = true;
        gridBlogs.Columns = "BlogID, BlogName, NodeID, DocumentCulture";

        // Get all possible columns to retrieve
        IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree");
        DocumentInfo di = new DocumentInfo();
        BlogInfo bi = new BlogInfo();
        gridBlogs.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(bi.ColumnNames.ToArray()), SqlHelperClass.MergeColumns(di.ColumnNames.ToArray())), SqlHelperClass.MergeColumns(nodeClass.ColumnNames.ToArray()));

        DataClassInfo dci = DataClassInfoProvider.GetDataClass("cms.blogpost");
        string classId = "";
        StringBuilder script = new StringBuilder();

        if (dci != null)
        {
            classId = dci.ClassID.ToString();
        }

        // Get script to redirect to new blog post page
        script.Append("function NewPost(parentId, culture) {",
                     "  if (parentId != 0) {",
                     "     parent.parent.parent.location.href = \"", ResolveUrl("~/CMSDesk/default.aspx"), "?section=content&action=new&nodeid=\" + parentId + \"&classid=", classId, " &culture=\" + culture;",
                     "}}");

        // Generate javascript code
        ltlScript.Text = ScriptHelper.GetScript(script.ToString());
    }
示例#30
0
 public override bool UpdateBlog(BlogInfo info)
 {
     return DbProvider.Instance().UpdateBlog(info);
 }
示例#31
0
 public abstract PagedCollection<BlogAlias> GetPagedBlogDomainAlias(BlogInfo blog, int pageIndex, int pageSize);
示例#32
0
        public override IPagedCollection<MetaTag> GetMetaTagsForBlog(BlogInfo blog, int pageIndex, int pageSize)
        {
            using (IDataReader reader = DbProvider.Instance().GetMetaTagsForBlog(blog, pageIndex, pageSize))
            {
                IPagedCollection<MetaTag> tags = new PagedCollection<MetaTag>();

                while(reader.Read())
                {
                    tags.Add(DataHelper.LoadMetaTag(reader));
                }
                reader.NextResult();
                tags.MaxItems = DataHelper.GetMaxItems(reader);
                return tags;
            }
        }
示例#33
0
        private static void EmailCommentToAdmin(FeedbackItem comment, BlogInfo currentBlog)
        {
            string blogTitle = currentBlog.Title;

            // create and format an email to the site admin with comment details
            EmailProvider im = EmailProvider.Instance();

            string fromEmail = comment.Email;
            if (String.IsNullOrEmpty(fromEmail))
                fromEmail = null;

            string to = currentBlog.Email;
            string from = fromEmail ?? im.AdminEmail;

            string subject = String.Format(CultureInfo.InvariantCulture, "Comment: {0} (via {1})", comment.Title, blogTitle);
            if (comment.FlaggedAsSpam)
                subject = "[SPAM Flagged] " + subject;

            string commenterUrl = "none given";
            if(comment.SourceUrl != null)
                commenterUrl = comment.SourceUrl.ToString();

            string bodyFormat = "{7}Comment from {0}" + Environment.NewLine
                                + "----------------------------------------------------" + Environment.NewLine
                                + "From:\t{1} <{2}>" + Environment.NewLine
                                + "Url:\t{3}" + Environment.NewLine
                                + "IP:\t{4}" + Environment.NewLine
                                + "====================================================" + Environment.NewLine + Environment.NewLine
                                + "{5}" + Environment.NewLine + Environment.NewLine
                                + "Source: {6}";

            string body = string.Format(CultureInfo.InvariantCulture, bodyFormat,
                                        blogTitle,
                                        comment.Author,
                                        fromEmail ?? "no email given",
                                        commenterUrl,
                                        comment.IpAddress,
                // we're sending plain text email by default, but body includes <br />s for crlf
                                        comment.Body.Replace("<br />", Environment.NewLine).Replace("&lt;br /&gt;", Environment.NewLine),
                                        currentBlog.UrlFormats.FeedbackFullyQualifiedUrl(comment.EntryId, comment.parentEntryName, comment.ParentDateCreated, comment),
                                        comment.FlaggedAsSpam ? "Spam Flagged " : string.Empty);

            try
            {
                SendEmailDelegate sendEmail = im.Send;
                AsyncHelper.FireAndForget(sendEmail, to, from, subject, body);
            }
            catch(Exception e)
            {
                log.Warn("Could not email comment to admin", e);
            }
        }
示例#34
0
        public override PagedCollection<BlogAlias> GetPagedBlogDomainAlias(BlogInfo blog, int pageIndex, int pageSize)
        {
            IDataReader reader = DbProvider.Instance().GetPagedBlogDomainAliases(blog.Id, pageIndex, pageSize);
            try
            {
                PagedCollection<BlogAlias> pec = new PagedCollection<BlogAlias>();
                while (reader.Read())
                {
                    pec.Add(DataHelper.LoadBlogAlias(reader));
                }
                reader.NextResult();
                pec.MaxItems = DataHelper.GetMaxItems(reader);
                return pec;

            }
            finally
            {
                reader.Close();
            }
        }
示例#35
0
 /// <summary>
 /// Creates a new <see cref="BlogHiddenException"/> instance.
 /// </summary>
 /// <param name="hidden">Hidden.</param>
 /// <param name="blogId"></param>
 public BlogHiddenException(BlogInfo hidden, int blogId)
     : base()
 {
     _hiddenBlog = hidden;
     _blogId = blogId;
 }
示例#36
0
 public Task <bool> SetBlogInfo(BlogInfo blogInfo)
 {
     return(Task.FromResult(_blogInfoCollection.Upsert(blogInfo)));
 }
示例#37
0
        public static BlogInfo LoadConfigData(IDataReader reader)
        {
            BlogInfo info = new BlogInfo();
            info.Author = ReadString(reader, "Author");
            info.Id = ReadInt32(reader, "BlogId");
            info.Email = ReadString(reader, "Email");
            info.Password = ReadString(reader, "Password");
            info.OpenIDUrl = ReadString(reader, "OpenIDUrl");
            info.CardSpaceHash = ReadString(reader, "CardSpaceHash");

            info.SubTitle = ReadString(reader, "SubTitle");
            info.Title = ReadString(reader, "Title");
            info.UserName = ReadString(reader, "UserName");
            info.TimeZoneId = ReadInt32(reader, "TimeZone");
            info.ItemCount = ReadInt32(reader, "ItemCount");
            info.CategoryListPostCount = ReadInt32(reader, "CategoryListPostCount");
            info.Language = ReadString(reader, "Language");

            info.PostCount = ReadInt32(reader, "PostCount");
            info.CommentCount = ReadInt32(reader, "CommentCount");
            info.StoryCount = ReadInt32(reader, "StoryCount");
            info.PingTrackCount = ReadInt32(reader, "PingTrackCount");
            info.News = ReadString(reader, "News");
            info.TrackingCode = ReadString(reader, "TrackingCode");

            info.LastUpdated = ReadDate(reader, "LastUpdated", new DateTime(2003, 1 , 1));
            info.Host = ReadString(reader, "Host");
            // The Subfolder property is stored in the Application column.
            // This is a result of the legacy schema.
            info.Subfolder = ReadString(reader, "Application");

            info.Flag = (ConfigurationFlags)(ReadInt32(reader, "Flag"));

            info.Skin = new SkinConfig();
            info.Skin.TemplateFolder = ReadString(reader, "Skin");
            info.Skin.SkinStyleSheet = ReadString(reader, "SkinCssFile");
            info.Skin.CustomCssText = ReadString(reader, "SecondaryCss");
            info.MobileSkin = new SkinConfig();
            info.MobileSkin.TemplateFolder = ReadString(reader, "MobileSkin");
            info.MobileSkin.SkinStyleSheet = ReadString(reader, "MobileSkinCssFile");

            info.OpenIDUrl = ReadString(reader, "OpenIDUrl");
            info.OpenIDServer = ReadString(reader, "OpenIDServer");
            info.OpenIDDelegate = ReadString(reader, "OpenIDDelegate");
            info.CardSpaceHash = ReadString(reader, "CardSpaceHash");

            info.LicenseUrl = ReadString(reader, "LicenseUrl");

            info.DaysTillCommentsClose = ReadInt32(reader, "DaysTillCommentsClose", int.MaxValue);
            info.CommentDelayInMinutes = ReadInt32(reader, "CommentDelayInMinutes");
            info.NumberOfRecentComments = ReadInt32(reader, "NumberOfRecentComments");
            info.RecentCommentsLength = ReadInt32(reader, "RecentCommentsLength");
            info.FeedbackSpamServiceKey = ReadString(reader, "AkismetAPIKey");
            info.FeedBurnerName = ReadString(reader, "FeedBurnerName");

            info.BlogGroupId = ReadInt32(reader, "BlogGroupId");
            info.BlogGroupTitle = ReadString(reader, "BlogGroupTitle");
            return info;
        }
        // Get the blog information from the input XML data,
        //  and return it as BlogInfo object
        private BlogInfo parseBlogInfo(string xmlData, string blogLink)
        {
            try
            {
                using (var xmlStream = xmlData.ToStream())
                {
                    XDocument xmlDoc = XDocument.Load(xmlStream);

                    // Get the blog information XML node
                    var blogInfoXML = xmlDoc.Element("rss").Element("channel");

                    // Get the blog description and title
                    var blogInfo = new BlogInfo();
                    blogInfo.Description = blogInfoXML.Element("description").Value.ScrubHtml();
                    blogInfo.Title = blogInfoXML.Element("title").Value.ScrubHtml();
                    return blogInfo;
                }
            }
            catch (Exception ex)
            {
                _logger.Warn("Unable to parse blog info from {0}\nException: {1}\nStackTrace: {2}",
                                        blogLink, ex.Message, ex.StackTrace);
                return null;
            }
        }