using Microsoft.SharePoint; using Microsoft.SharePoint.Publishing; using Microsoft.SharePoint.Utilities; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using Taloyhtio.CondoUpdate.Common; namespace CondoUpdate.ResponsiveLayout.AddAvailablePageLayoutsAc { public class UpdaterImpl : ICondoUpdater { public event EventHandler OnNotify; public void Update(object args) { string url = args as string; if (string.IsNullOrEmpty(url)) { this.warn("Url is empty"); return; } try { this.updateImpl(url); } catch (Exception x) { this.error("Error occured during updating of Condo '{0}':\n{1}\n{2}", url, x.Message, x.StackTrace); } } private void updateImpl(string url) { using (var site = new SPSite(url)) { using (var web = site.RootWeb) { if (!web.Exists) { this.warn("Web site '{0}' doesn't exist. It will be ignored", url); return; } Thread.CurrentThread.CurrentUICulture = new CultureInfo((int)web.Language); this.addAvailablePageLayouts(site); } } } private void addAvailablePageLayouts(SPSite site) { // page templates var pweb = PublishingWeb.GetPublishingWeb(site.RootWeb); var pageLayouts = new List(pweb.GetAvailablePageLayouts()); var psite = new PublishingSite(site); var allPageLayouts = psite.GetPageLayouts(true); if (!pageLayouts.Any(l => string.Compare(l.Name, "tallier_responsive_layout.aspx", true) == 0)) { var pl = allPageLayouts.FirstOrDefault(l => string.Compare(l.Name, "tallier_responsive_layout.aspx", true) == 0); if (pl != null) { pageLayouts.Add(pl); } } if (!pageLayouts.Any(l => string.Compare(l.Name, "tallier_responsive_layout_wide.aspx", true) == 0)) { var pl = allPageLayouts.FirstOrDefault(l => string.Compare(l.Name, "tallier_responsive_layout_wide.aspx", true) == 0); if (pl != null) { pageLayouts.Add(pl); } } pweb.SetAvailablePageLayouts(pageLayouts.ToArray(), true); pweb.Update(); this.notify(LogLevel.Info, "applied page layouts"); } #region notifier private void warn(string msg, params object[] args) { this.notify(LogLevel.Warn, msg, args); } private void error(string msg, params object[] args) { this.notify(LogLevel.Error, msg, args); } private void notify(LogLevel level, string msg, params object[] args) { this.notify(level, string.Format(msg, args)); } private void notify(LogLevel level, string msg) { if (this.OnNotify != null) { this.OnNotify(this, new LogEventArgs { LogLevel = level, Message = msg }); } } #endregion } }