Ejemplo n.º 1
0
        public string GetEditorTemplateHtml(BlogEditingTemplateType templateType, bool forceRTL)
        {
            SettingsPersisterHelper templates = _editorTemplateSettings.GetSubSettings(EDITOR_TEMPLATES_KEY);
            string templateHtmlFile           = templates.GetString(templateType.ToString(), null);

            // Sometimes templateHtmlFile is relative, sometimes it is already absolute (from older builds).
            templateHtmlFile = MakeAbsolute(templateHtmlFile);

            if (templateHtmlFile != null && File.Exists(templateHtmlFile))
            {
                string templateHtml;
                using (StreamReader reader = new StreamReader(templateHtmlFile, Encoding.UTF8))
                    templateHtml = reader.ReadToEnd();

                if (File.Exists(templateHtmlFile + ".path"))
                {
                    string origPath = File.ReadAllText(templateHtmlFile + ".path");
                    string newPath  = Path.Combine(Path.GetDirectoryName(templateHtmlFile), Path.GetFileName(origPath));
                    string newUri   = UrlHelper.SafeToAbsoluteUri(new Uri(newPath));
                    templateHtml = templateHtml.Replace(origPath, newUri);
                }

                return(templateHtml);
            }
            else
            {
                return(BlogEditingTemplate.GetDefaultTemplateHtml(forceRTL, templateType != BlogEditingTemplateType.Normal));
            }
        }
        /// <summary>
        /// Loads the blog editing template.
        /// </summary>
        /// <param name="blogId"></param>
        /// <returns></returns>
        internal static string LoadBlogTemplate(string blogId, BlogEditingTemplateType templateType, bool forceRTL)
        {
            using (PostHtmlEditingSettings templateSettings = new PostHtmlEditingSettings(blogId))
            {
                string html = templateSettings.GetEditorTemplateHtml(templateType, forceRTL);
                if (html == null || html == String.Empty ||
                    html.IndexOf(BlogEditingTemplate.POST_TITLE_MARKER) == -1 ||
                    html.IndexOf(BlogEditingTemplate.POST_BODY_MARKER) == -1)
                {
                    html = BlogEditingTemplate.GetDefaultTemplateHtml(forceRTL, true);
                }

                return(html);
            }
        }
        /// <summary>
        /// Loads the blog editing template.
        /// </summary>
        /// <param name="blogId"></param>
        /// <returns></returns>
        internal static string LoadBlogTemplate(string blogId, BlogEditingTemplateType templateType, bool forceRTL)
        {
            using (PostHtmlEditingSettings templateSettings = new PostHtmlEditingSettings(blogId))
            {
                string html = templateSettings.GetEditorTemplateHtml(templateType, forceRTL);
                if (html == null || html == String.Empty ||
                    html.IndexOf(BlogEditingTemplate.POST_TITLE_MARKER) == -1 ||
                    html.IndexOf(BlogEditingTemplate.POST_BODY_MARKER) == -1)
                {
                    html = BlogEditingTemplate.GetDefaultTemplateHtml(forceRTL, true);
                }

                return html;
            }
        }
        public string GetEditorTemplateHtml(BlogEditingTemplateType templateType, bool forceRTL)
        {
            SettingsPersisterHelper templates = _editorTemplateSettings.GetSubSettings(EDITOR_TEMPLATES_KEY);
            string templateHtmlFile           = templates.GetString(templateType.ToString(), null);

            // Sometimes templateHtmlFile is relative, sometimes it is already absolute (from older builds).
            templateHtmlFile = MakeAbsolute(templateHtmlFile);

            if (templateHtmlFile != null && File.Exists(templateHtmlFile))
            {
                string templateHtml;
                using (StreamReader reader = new StreamReader(templateHtmlFile, Encoding.UTF8))
                    templateHtml = reader.ReadToEnd();

                if (File.Exists(templateHtmlFile + ".path"))
                {
                    string origPath = File.ReadAllText(templateHtmlFile + ".path");
                    string newPath  = Path.Combine(Path.GetDirectoryName(templateHtmlFile), Path.GetFileName(origPath));
                    string newUri   = UrlHelper.SafeToAbsoluteUri(new Uri(newPath));
                    templateHtml = templateHtml.Replace(origPath, newUri);
                }

                /*Parse meta tags in order to set CSS3 compatibility*/
                Regex metatag = new Regex(@"<(?i:meta)(\s)+(?i:http-equiv)(\s)*=""(?:X-UA-Compatible)""(\s)+(?i:content)(\s)*=""(?i:IE=edge)""(\s)*/>");
                Match match   = metatag.Match(templateHtml);

                if (!match.Success)
                {
                    // prepend the metatag to make css3 compatible at least on edge (Windows 8+)
                    int i = templateHtml.IndexOf("<HEAD>", StringComparison.OrdinalIgnoreCase);
                    if (i > 0)
                    {
                        templateHtml = (templateHtml.Substring(0, i + 6)
                                        + "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />"
                                        + templateHtml.Substring(i + 6));
                    }
                }


                return(templateHtml);
            }
            else
            {
                return(BlogEditingTemplate.GetDefaultTemplateHtml(forceRTL, templateType != BlogEditingTemplateType.Normal));
            }
        }
 public BlogEditingTemplateFile(BlogEditingTemplateType type, string file)
 {
     TemplateType = type;
     TemplateFile = file;
 }
        public string GetEditorTemplateHtml(BlogEditingTemplateType templateType, bool forceRTL)
        {
            SettingsPersisterHelper templates = _editorTemplateSettings.GetSubSettings(EDITOR_TEMPLATES_KEY);
            string templateHtmlFile           = templates.GetString(templateType.ToString(), null);

            // Sometimes templateHtmlFile is relative, sometimes it is already absolute (from older builds).
            templateHtmlFile = MakeAbsolute(templateHtmlFile);

            if (templateHtmlFile != null && File.Exists(templateHtmlFile))
            {
                string templateHtml;
                using (StreamReader reader = new StreamReader(templateHtmlFile, Encoding.UTF8))
                    templateHtml = reader.ReadToEnd();

                if (File.Exists(templateHtmlFile + ".path"))
                {
                    string origPath = File.ReadAllText(templateHtmlFile + ".path");
                    string newPath  = Path.Combine(Path.GetDirectoryName(templateHtmlFile), Path.GetFileName(origPath));
                    string newUri   = UrlHelper.SafeToAbsoluteUri(new Uri(newPath));
                    templateHtml = templateHtml.Replace(origPath, newUri);
                }

                /* Parse meta tags in order to set MSHTML emulation for IE9
                 * As of Internet Explorer 10, support for element behaviors have been removed.
                 * Core OLW functionality, such as table management, currently rely on these mechanisms.
                 * An alternative to Element Behaviors must be found before we can push the IE version forward to allow for newer web standards. */

                // Search for an existing X-UA-Compatible tag in the template
                Regex metatag = new Regex(@"<(?i:meta)(?:\s)+(?i:http-equiv)(?:\s)*=""(?:X-UA-Compatible)""(?:\s)+(?i:content)(?:\s)*=""(\S*)""(?:\s)*/>");
                Match match   = metatag.Match(templateHtml);

                if (match.Success && match.Groups.Count > 1)
                {
                    // There already exists a 'X-UA-Compatible' meta tag in the template, modify it
                    // Grab info on the existing 'content' value
                    var contentVal = match.Groups[1];
                    // Remove the content value from the template
                    var templateContentRemoved = templateHtml.Remove(contentVal.Index, contentVal.Length);
                    // Add the IE9 emulation string into the HTML template
                    templateHtml = templateContentRemoved.Insert(contentVal.Index, UA_COMPATIBLE_STRING);
                }
                else
                {
                    // Prepend meta tag for IE9 emulation
                    int i = templateHtml.IndexOf("<HEAD>", StringComparison.OrdinalIgnoreCase);
                    if (i > 0)
                    {
                        templateHtml = (templateHtml.Substring(0, i + 6)
                                        + $"<meta http-equiv=\"X-UA-Compatible\" content=\"{UA_COMPATIBLE_STRING}\" />"
                                        + templateHtml.Substring(i + 6));
                    }
                }


                return(templateHtml);
            }
            else
            {
                return(BlogEditingTemplate.GetDefaultTemplateHtml(forceRTL, templateType != BlogEditingTemplateType.Normal));
            }
        }
        public string GetEditorTemplateHtml(BlogEditingTemplateType templateType, bool forceRTL)
        {
            SettingsPersisterHelper templates = _editorTemplateSettings.GetSubSettings(EDITOR_TEMPLATES_KEY);
            string templateHtmlFile = templates.GetString(templateType.ToString(), null);
            // Sometimes templateHtmlFile is relative, sometimes it is already absolute (from older builds).
            templateHtmlFile = MakeAbsolute(templateHtmlFile);

            if (templateHtmlFile != null && File.Exists(templateHtmlFile))
            {
                string templateHtml;
                using (StreamReader reader = new StreamReader(templateHtmlFile, Encoding.UTF8))
                    templateHtml = reader.ReadToEnd();

                if (File.Exists(templateHtmlFile + ".path"))
                {
                    string origPath = File.ReadAllText(templateHtmlFile + ".path");
                    string newPath = Path.Combine(Path.GetDirectoryName(templateHtmlFile), Path.GetFileName(origPath));
                    string newUri = UrlHelper.SafeToAbsoluteUri(new Uri(newPath));
                    templateHtml = templateHtml.Replace(origPath, newUri);
                }

                return templateHtml;
            }
            else
            {
                return BlogEditingTemplate.GetDefaultTemplateHtml(forceRTL, templateType != BlogEditingTemplateType.Normal);
            }
        }
        /// <summary>
        /// Creates a set of BlogTemplateFiles using a specific region locator strategy.
        /// </summary>
        /// <param name="progress"></param>
        /// <param name="regionLocatorStrategy"></param>
        /// <param name="templateStrategies"></param>
        /// <param name="templateTypes"></param>
        /// <returns></returns>
        private BlogEditingTemplateFile[] GetBlogTemplateFiles(IProgressHost progress, BlogPostRegionLocatorStrategy regionLocatorStrategy, BlogEditingTemplateStrategy[] templateStrategies, BlogEditingTemplateType[] templateTypes)
        {
            BlogEditingTemplateFile[] blogTemplateFiles = null;
            try
            {
                regionLocatorStrategy.PrepareRegions(new ProgressTick(progress, 25, 100));

                ArrayList templateFiles = new ArrayList();
                ProgressTick tick = new ProgressTick(progress, 50, 100);
                for (int i = 0; i < templateTypes.Length; i++)
                {
                    ProgressTick parseTick = new ProgressTick(tick, 1, templateTypes.Length);
                    try
                    {
                        CheckCancelRequested(parseTick);
                        templateStrategy = templateStrategies[i];

                        // Parse the blog post HTML into an editing template.
                        // Note: we can't use MarkupServices to parse the document from a non-UI thread,
                        // so we have to execute the parsing portion of the template download operation on the UI thread.
                        string editingTemplate = ParseWebpageIntoEditingTemplate_OnUIThread(_parentControl, regionLocatorStrategy, new ProgressTick(parseTick, 1, 5));

                        // check for cancel
                        CheckCancelRequested(parseTick);

                        string baseUrl = HTMLDocumentHelper.GetBaseUrl(editingTemplate, _blogHomepageUrl);

                        // Download the template stylesheets and embedded resources (this lets the editing template load faster..and works offline!)
                        string templateFile = DownloadTemplateFiles(editingTemplate, baseUrl, new ProgressTick(parseTick, 4, 5));
                        templateFiles.Add(new BlogEditingTemplateFile(templateTypes[i], templateFile));

                    }
                    catch (Exception e)
                    {
                        Trace.WriteLine(String.Format(CultureInfo.CurrentCulture, "Failed to download template {0}: {1}", templateTypes[i].ToString(), e.ToString()));
                    }
                }
                if (templateFiles.Count > 0)
                    blogTemplateFiles = (BlogEditingTemplateFile[])templateFiles.ToArray(typeof(BlogEditingTemplateFile));
            }
            finally
            {
                regionLocatorStrategy.CleanupRegions(new ProgressTick(progress, 25, 100));
            }
            return blogTemplateFiles;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="progress"></param>
        /// <param name="targetTemplateTypes"></param>
        /// <param name="templateStrategies">equivalent strategies for manipulating the blog homepage DOM into an editing template type</param>
        /// <returns></returns>
        private BlogEditingTemplateFile[] DetectTemplates(IProgressHost progress, BlogEditingTemplateType[] targetTemplateTypes, BlogEditingTemplateStrategy[] templateStrategies)
        {
            RecentPostRegionLocatorStrategy recentPostLocatorStrategy =
                new RecentPostRegionLocatorStrategy(_blogClient, _blogAccount, _credentials, _blogHomepageUrl,
                                                    new PageDownloader(RequestPageDownload));

            TemporaryPostRegionLocatorStrategy tempPostLocatorStrategy =
                new TemporaryPostRegionLocatorStrategy(_blogClient, _blogAccount, _credentials, _blogHomepageUrl,
                                                       new PageDownloader(RequestPageDownload), new BlogPostRegionLocatorBooleanCallback(recentPostLocatorStrategy.HasBlogPosts));

            //setup the strategies for locating the title/body regions in the blog homepage.
            BlogPostRegionLocatorStrategy[] regionLocatorStrategies = new BlogPostRegionLocatorStrategy[]
                {
                    recentPostLocatorStrategy,
                    tempPostLocatorStrategy
                };

            // template files to return
            BlogEditingTemplateFile[] blogTemplateFiles = null;

            // try each strategy as necessary
            for (int i = 0; i < regionLocatorStrategies.Length && blogTemplateFiles == null; i++)
            {
                CheckCancelRequested(progress);

                //reset the progress for each iteration
                BlogPostRegionLocatorStrategy regionLocatorStrategy = regionLocatorStrategies[i];
                try
                {
                    blogTemplateFiles = GetBlogTemplateFiles(progress, regionLocatorStrategy, templateStrategies, targetTemplateTypes);
                    progress.UpdateProgress(100, 100);

                    //if any exception occured along the way, clear them since one of the template strategies
                    //was successful.
                    _exception = null;
                }
                catch (OperationCancelledException)
                {
                    // cancel just means our template will be String.Empty
                    _exception = null;
                }
                catch (BlogClientOperationCancelledException e)
                {
                    // cancel just means our template will be String.Empty
                    // (setting this exception here means that at least the user
                    // will be notified that they won't be able to edit with style)
                    _exception = e;
                }
                catch (WebException e)
                {
                    _exception = e;
                    Trace.WriteLine("Error occurred while downloading weblog style: " + e.ToString());
                    if (e.Response != null)
                    {
                        Trace.WriteLine(String.Format(CultureInfo.InvariantCulture, "Blogpost homepage request failed: {0}", _blogHomepageUrl));
                        //Debug.WriteLine(HttpRequestHelper.DumpResponse((HttpWebResponse)e.Response));
                    }
                }
                catch (Exception e)
                {
                    _exception = e;
                    Trace.WriteLine("Error occurred while downloading weblog style: " + e.ToString());
                }

            }

            // return the detected tempaltes
            return blogTemplateFiles;
        }
 public BlogEditingTemplateFile(BlogEditingTemplateType type, string file)
 {
     TemplateType = type;
     TemplateFile = file;
 }