Andrey on .NET | Прикрепленные сайты. Часть 3 – Исходый код

Прикрепленные сайты. Часть 3 – Исходый код

Осталось только привести полный исходный код для созданного в прошлой части расширения.

Файл PinnedSiteSupport.js

Данный файл по умолчанию располагается в папке \Scripts\PinnedSite.

/// Copyright (c) 2011 Andrey Veselov. All rights reserved.
/// WebSite: http://andrey.moveax.ru 
/// Email: andrey@moveax.ru
/// This source is subject to the Microsoft Reciprocal License (Ms-RL).

addIE9PinnedCategories = function (title) {
    var isPinnedSiteMode = window.external && "msIsSiteMode" in window.external && window.external.msIsSiteMode();

    if (isPinnedSiteMode) {
        window.external.msSiteModeCreateJumplist(title);
        window.external.msSiteModeClearJumplist();
        var posts = getNewPostsForPinnedSite();
        for (i = posts.length - 1; i >= 0; i--) {
            window.external.msSiteModeAddJumpListItem(
                posts[i].name, posts[i].postUrl, posts[i].iconUrl);
        }
        window.external.msSiteModeShowJumplist();
    }
};

Файл PinnedSiteSupport.cs

Данный файл необходимо разместить в папке \App_Code\Extensions.

/// Copyright (c) 2011 Andrey Veselov. All rights reserved.
/// WebSite: http://andrey.moveax.ru 
/// Email: andrey@moveax.ru
/// This source is subject to the Microsoft Reciprocal License (Ms-RL).

namespace App_Code.Extensions
{
    using System;
    using System.Data;
    using System.Text;
    using System.Web;
    using System.Web.UI.HtmlControls;
    using BlogEngine.Core;
    using BlogEngine.Core.Web.Controls;
    using BlogEngine.Core.Web.Extensions;
    using Page = System.Web.UI.Page;

    [Extension(
        description: "Adds support for IE9 Pinned mode",
        version: "0.8",
        author: "<a target=\"_new\" href=\"http://andrey.moveax.ru/\">Andrey Veselov</a>")]
    public class PinnedSiteSupport
    {
        private const string ExtensionName = "PinnedSiteSupport";

        /// Settings storage
        private static ExtensionSettings _siteSettings;
        private static ExtensionSettings _jumpListSettings;
        private static ExtensionSettings _jumpListIcons;
        private static ExtensionSettings _tasksSettings;
        private static ExtensionSettings _tasksList;
        
        /// <summary>Default static parameterless constructor.</summary>
        static PinnedSiteSupport()
        {
            // Subscribe to blog "serving" events
            BlogEngine.Core.Page.Serving += new EventHandler<ServingEventArgs>(BlogServingHandler);
            BlogEngine.Core.Post.Serving += new EventHandler<ServingEventArgs>(BlogServingHandler);
        }

        /// <summary>The event handler that is triggered every time a post or page is served to a client.</summary>
        private static void BlogServingHandler(object sender, ServingEventArgs e)
        {
            HttpContext context = HttpContext.Current;

            // Checking the browser version to see if it's IE9 or higher.
            var browser = context.Request.Browser;
            var isIE9orHigher = browser.Browser.Equals("IE") && (browser.MajorVersion >= 9);
            if (!isIE9orHigher) {
                return;
            }
            
            Page page = context.CurrentHandler as Page;
            if ((page == null) || (context.Items[ExtensionName] != null)) {
                return;
            }

            PinnedSiteSupport.InitSettings();

            PinnedSiteSupport.AddSiteProperties(page);
            PinnedSiteSupport.AddJumpListItems(page);
            PinnedSiteSupport.AddTasks(page);

            // Set the flag in order to add items once per page (not once per post).
            context.Items[ExtensionName] = new object();
        }

        /// <summary>Adds site properties as meta tags into the current page.</summary>
        private static void AddSiteProperties(Page page)
        {
            if (_siteSettings.GetSingleValue("enabled").Equals(false.ToString())) {
                return;
            }

            PinnedSiteSupport.InsertMetaTag(
                page,
                "application-name",
                _siteSettings.GetSingleValue("application-name"));

            PinnedSiteSupport.InsertMetaTag(
                page,
                "msapplication-tooltip",
                _siteSettings.GetSingleValue("msapplication-tooltip"));

            PinnedSiteSupport.InsertMetaTag(
                page,
                "msapplication-starturl",
                _siteSettings.GetSingleValue("msapplication-starturl"));

            PinnedSiteSupport.InsertMetaTag(
                page,
                "msapplication-navbutton-color",
                _siteSettings.GetSingleValue("msapplication-navbutton-color"));

            string defWidth = _siteSettings.GetSingleValue("msapplication-window-minWidth");
            string defHeight = _siteSettings.GetSingleValue("msapplication-window-minHeight");

            if (!string.IsNullOrEmpty(defWidth) && !string.IsNullOrEmpty(defHeight)) {
                PinnedSiteSupport.InsertMetaTag(
                    page,
                    "msapplication-window-min",
                    string.Format(@"width={0};height={1}", defWidth, defHeight));
            }
        }

        /// <summary>Adds JumpList items into the current page.</summary>
        private static void AddJumpListItems(Page page)
        {
            if (_jumpListSettings.GetSingleValue("enabled").Equals(false.ToString())) {
                return;
            }

            PinnedSiteSupport.InsertJavaScript(page, PinnedSiteSupport.CreateJSPostsList());
            PinnedSiteSupport.InsertJavaScriptRef(page, "PinnedSiteSupport.js");
            PinnedSiteSupport.InsertJavaScript(
                page,
                string.Format(
                    "addIE9PinnedCategories(\"{0}\");",
                    _jumpListSettings.GetSingleValue("title")));
        }

        /// <summary>Adds Tasks list into the current page.</summary>
        private static void AddTasks(Page page)
        {
            if (_tasksSettings.GetSingleValue("enabled").Equals(false.ToString())) {
                return;
            }

            var tasks = _tasksList.GetDataTable();
            foreach (DataRow task in tasks.Rows) {
                string value = string.Format("name={0};action-uri={1};icon-uri={2}",
                    task["name"],
                    task["action-uri"],
                    task["icon-uri"]);

                PinnedSiteSupport.InsertMetaTag(page, "msapplication-task", value);
            }
        }

        /// <summary>Initalize extension settings.</summary>
        private static void InitSettings()
        {
            #region Site properties

            var siteSettings = new ExtensionSettings("Site properties");
            siteSettings.IsScalar = true;

            siteSettings.AddParameter("enabled", "Enable Meta tags", 10, true, false, ParameterType.Boolean);

            siteSettings.AddParameter("application-name", "Site name", 128, true, false, ParameterType.String);
            siteSettings.AddValue("application-name", string.Empty);

            siteSettings.AddParameter("msapplication-tooltip", "Tooltip", 128, true, false, ParameterType.String);
            siteSettings.AddValue("msapplication-tooltip", string.Empty);

            siteSettings.AddParameter("msapplication-starturl", "Start url", 255, true, false, ParameterType.String);
            siteSettings.AddValue("msapplication-starturl", Utils.AbsoluteWebRoot.AbsoluteUri);

            siteSettings.AddParameter("msapplication-navbutton-color", "Navigation button color", 128, true, false, ParameterType.String);

            siteSettings.AddParameter("msapplication-window-minWidth", "Default window width");
            siteSettings.AddValue("msapplication-window-minWidth", 1024);

            siteSettings.AddParameter("msapplication-window-minHeight", "Default window height");
            siteSettings.AddValue("msapplication-window-minHeight", 720);

            _siteSettings = ExtensionManager.InitSettings(ExtensionName, siteSettings);

            #endregion

            #region JumpList Item settings

            var jumpList = new ExtensionSettings("JumpList Items");
            jumpList.IsScalar = true;

            jumpList.AddParameter("enabled", "Enable JumpList items", 10, true, false, ParameterType.Boolean);

            jumpList.AddParameter("title", "Title", 64, true, false, ParameterType.String);
            jumpList.AddParameter("iconUrl", "Default icon URL (optional)", 255, true, false, ParameterType.String);

            jumpList.AddParameter("daysOffset", "Days offset", 3, true, false, ParameterType.Integer);
            jumpList.AddValue("daysOffset", 7);

            jumpList.AddParameter("jsFolder", "JavaScript folder (relative to website root)", 255, true, false, ParameterType.String);
            jumpList.AddValue("jsFolder", "Scripts/PinnedSite/");

            _jumpListSettings = ExtensionManager.InitSettings(ExtensionName, jumpList);

            #endregion

            #region Jumplist icons

            var jumpListIcons = new ExtensionSettings("JumpList Icons");

            jumpListIcons.AddParameter("urlPart", "Part of the URL", 64, true, true, ParameterType.String);
            jumpListIcons.AddParameter("iconUrl", "Icon URL", 255, true, false, ParameterType.String);

            _jumpListIcons = ExtensionManager.InitSettings(ExtensionName, jumpListIcons);

            #endregion

            #region Tasks settings

            var tasks = new ExtensionSettings("Tasks");
            tasks.IsScalar = true;

            tasks.AddParameter("enabled", "Enable tasks", 10, true, false, ParameterType.Boolean);

            _tasksSettings = ExtensionManager.InitSettings(ExtensionName, tasks);

            var tasksList = new ExtensionSettings("Tasks List");

            tasksList.AddParameter("name", "Name", 32, true, false, ParameterType.String);
            tasksList.AddParameter("action-uri", "Action URL", 255, true, true, ParameterType.String);
            tasksList.AddParameter("icon-uri", "Icon URL (optional)", 255, false, false, ParameterType.String);

            _tasksList = ExtensionManager.InitSettings(ExtensionName, tasksList);

            #endregion
        }

        #region Support methods

        /// <summary>Builds the post list.</summary>
        private static string CreateJSPostsList()
        {
            int daysOffset = 7;
            Int32.TryParse(_jumpListSettings.GetSingleValue("daysOffset"), out daysOffset);

            var ie9js = new StringBuilder();
            ie9js.Append("getNewPostsForPinnedSite = function () { return [");

            // get posts list
            var timeOffset = new TimeSpan(days: daysOffset, hours: 0, minutes: 0, seconds: 0);
            var posts = Post.GetPostsByDate(DateTime.Now - timeOffset, DateTime.Now);

            foreach (var post in posts) {
                // get icon for the post
                string iconUrl = null;
                var icons = _jumpListIcons.GetDataTable();
                foreach (DataRow icon in icons.Rows) {
                    if (post.AbsoluteLink.ToString().IndexOf((string)icon["urlPart"]) != -1) {
                        iconUrl = (string)icon["iconUrl"];
                        break;
                    }
                }

                // or use default icon
                if (string.IsNullOrEmpty(iconUrl)) {
                    iconUrl = _jumpListSettings.GetSingleValue("iconUrl");
                }

                ie9js.Append(string.Format(
                    "{{ name: \"{0}\", postUrl: \"{1}\", iconUrl: \"{2}\" }},",
                    post.Title,
                    post.AbsoluteLink,
                    iconUrl));
            }

            ie9js.Remove(ie9js.Length - 1, 1); // remove last comma
            ie9js.AppendLine("]; };");

            return ie9js.ToString();
        }

        /// <summary>Inserts the meta tag element at the top of page.</summary>
        private static void InsertMetaTag(Page page, string metaName, string value)
        {
            if (string.IsNullOrEmpty(value)) {
                return;
            }

            HtmlGenericControl metaTag = new HtmlGenericControl("meta");
            metaTag.Attributes["name"] = metaName;
            metaTag.Attributes["content"] = value;
            page.Header.Controls.Add(metaTag);
        }

        /// <summary>Inserts the JavaScript code into the page.</summary>
        private static void InsertJavaScript(Page page, string script)
        {
            HtmlGenericControl js = new HtmlGenericControl("script");
            js.Attributes["type"] = "text/javascript";
            js.InnerHtml = script;
            page.Header.Controls.Add(js);
        }

        /// <summary>Inserts the JavaScript code reference into the page.</summary>
        private static void InsertJavaScriptRef(Page page, string srcFile)
        {
            string scriptUrl = HttpContext.Current.Server.UrlPathEncode(
                string.Format(
                    "{0}{1}",
                    _jumpListSettings.GetSingleValue("jsFolder"),
                    srcFile));

            HtmlGenericControl js = new HtmlGenericControl("script");
            js.Attributes["type"] = "text/javascript";
            js.Attributes["src"] = string.Format("{0}{1}", Utils.RelativeWebRoot, scriptUrl);
            page.Header.Controls.Add(js);
        }

        #endregion
    }
}

Добавить комментарий