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

129 lines
4.8 KiB
C#

using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Navigation;
using Microsoft.SharePoint.Publishing;
using Taloyhtio.CondoUpdate.Common;
using Microsoft.SharePoint.Publishing.Navigation;
namespace CondoUpdate.ResponsiveLayout.PmcRenameFrontPage
{
public class UpdaterImpl:ICondoUpdater
{
private const string PageTitle = "Etusivu";
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.changeGlobalNavigation(url, PageTitle);
}
private void changeGlobalNavigation(string url, string pageTitle)
{
if (string.IsNullOrEmpty(url)) return;
try
{
SPSecurity.RunWithElevatedPrivileges(() =>
{
using (var site = new SPSite(url))
{
using (var web = site.RootWeb)
{
if (!web.Exists)
{
return;
}
bool allowUnsafeUpdatesPmc = web.AllowUnsafeUpdates;
web.AllowUnsafeUpdates = true;
var pweb = PublishingWeb.GetPublishingWeb(web);
var globalNavigation = pweb.Navigation.GlobalNavigationNodes;
var nodePage = globalNavigation.Cast<SPNavigationNode>().FirstOrDefault(n => (n.Title.ToLower().EndsWith(" oy") || n.Title.ToLower().EndsWith(" ky")) && n.IsVisible == true);
if (nodePage != null)
{
nodePage.Delete();
}
else
{
this.warn("'{0}' Pmc name navigation item is not found", pageTitle);
}
var etusivuNode = globalNavigation.Cast<SPNavigationNode>().FirstOrDefault(p => p.Title.Equals(pageTitle) && p.IsVisible == true);
if (etusivuNode == null)
{
var node = SPNavigationSiteMapNode.CreateSPNavigationNode(pageTitle, web.Url, NodeTypes.Heading, globalNavigation);
var dt = DateTime.Now;
if (node != null)
{
node.Properties["CreatedDate"] = dt;
node.Properties["LastModifiedDate"] = dt;
node.Properties["Description"] = "";
node.Properties["Target"] = "";
node.Properties["Taloyhtio"] = "1";
node.Update();
node.MoveToFirst(globalNavigation);
}
}
else
{
this.warn("'{0}' navigation node already exists", pageTitle);
//etusivuNode.Delete();
}
web.Update();
web.AllowUnsafeUpdates = allowUnsafeUpdatesPmc;
}
}
});
}
catch (Exception x)
{
this.error("Error occured when rename front page on {0} error: {1} {2}", url, x.Message,
x.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 });
}
}
}
}