Taylohtio/CondoUpdate/CondoUpdate.ResponsiveLayou.../UpdaterImpl.cs

118 lines
3.9 KiB
C#

using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.SharePoint;
using Taloyhtio.CondoUpdate.Common;
namespace CondoUpdate.ResponsiveLayout.EnableResponsiveLayoutAc
{
public class UpdaterImpl:ICondoUpdater
{
private readonly Guid WEB_FEATURE_ID = new Guid("98523631-0ec3-4185-8d28-61c42712ca56");
public event EventHandler<LogEventArgs> 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)
{
this.enableResponsiveLayout(url);
}
private void enableResponsiveLayout(string url)
{
try
{
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);
if (!web.Site.Features.Any(f => f.DefinitionId.Equals(WEB_FEATURE_ID)))
{
web.Site.Features.Add(WEB_FEATURE_ID, true);
}
else
{
this.warn("Feature already activated on PMC '{0}', ignore", web.Url);
}
bool siteMaster = web.CustomMasterUrl.EndsWith("tallier_responsive_layout.master");
bool systemMaster = web.MasterUrl.EndsWith("tallier_responsive_layout_system.master");
if (!siteMaster || !systemMaster)
{
bool webAllowUnsafeUpdates = web.AllowUnsafeUpdates;
web.AllowUnsafeUpdates = true;
if (!siteMaster)
web.CustomMasterUrl = web.CustomMasterUrl.Replace(Path.GetFileName(web.CustomMasterUrl),
"tallier_responsive_layout.master");
if (!systemMaster)
web.MasterUrl = web.MasterUrl.Replace(Path.GetFileName(web.MasterUrl),
"tallier_responsive_layout_system.master");
web.Update();
web.AllowUnsafeUpdates = webAllowUnsafeUpdates;
}
}
}
}
catch (Exception ex)
{
this.error("Error occured when update '{0}' site:\n{1}\n{2}", url, ex.Message,
ex.StackTrace);
}
}
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 });
}
}
}
}