using Microsoft.SharePoint; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Taloyhtio.CondoUpdate.Common; namespace CondoUpdate.ResponsiveLayout.PmcMasterPage { public class UpdaterImpl : ICondoUpdater { private const string CONDO_PREFIX = "as oy "; private const string CONDO_WEB_TEMPLATE_NAME = "TaloyhtioCondoSite"; private const int CONDO_SITE_WEB_TEMPLATE_ID = 10101; private const short CONDO_WEB_CONFIGURATION = 0; 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.fixWebs(web); } } } private void fixWebs(SPWeb web) { //this.fixWeb(web); foreach (SPWeb subWeb in web.Webs) { if (!IsCondo(subWeb)) { this.fixWeb(subWeb); } } } private void fixWeb(SPWeb web) { bool oldAllowUnsafe = web.AllowUnsafeUpdates; web.AllowUnsafeUpdates = true; // first, explicitly set new masterpages web.CustomMasterUrl = web.CustomMasterUrl.Replace(Path.GetFileName(web.CustomMasterUrl), "taloyhtio_responsive_layout.master"); web.MasterUrl = web.MasterUrl.Replace(Path.GetFileName(web.MasterUrl), "taloyhtio_responsive_layout_system.master"); web.AllProperties["__InheritsMasterUrl"] = "False"; web.AllProperties["__InheritsCustomMasterUrl"] = "False"; web.Update(); // then force web to inherit masterpages web.AllProperties["__InheritsMasterUrl"] = "True"; web.AllProperties["__InheritsCustomMasterUrl"] = "True"; web.Update(); web.AllowUnsafeUpdates = oldAllowUnsafe; } public static bool IsCondo(SPWeb web) { try { if (web == null) { return false; } return web.Title.ToLower().StartsWith(CONDO_PREFIX) || (string.Compare(web.WebTemplate, CONDO_WEB_TEMPLATE_NAME, true) == 0 && web.WebTemplateId == CONDO_SITE_WEB_TEMPLATE_ID) && web.Configuration == CONDO_WEB_CONFIGURATION; } catch (Exception) { return false; } } #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 } }