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

257 lines
10 KiB
C#

using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
using Taloyhtio.CondoUpdate.Common;
using WebPart = System.Web.UI.WebControls.WebParts.WebPart;
namespace CondoUpdate.ResponsiveLayout.HallitukselleConfigureWebParts
{
public class UpdaterImpl:ICondoUpdater
{
private const string TitleOld = "Isännöitsijä tiedottaa - Hallitustiedotteet";
private const string TitleOld2 = "Isännöitsijätoimisto tiedottaa - Hallitustiedotteet";
private const string TitleNew = "Isännöitsijältä hallituksille";
private const string ResourceName = "CondoUpdate.ResponsiveLayout.HallitukselleConfigureWebParts.template.xslt";
private string xslStyleSheet = null;
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)
{
configureWebParts(url);
}
private void configureWebParts(string url)
{
try
{
SPSecurity.RunWithElevatedPrivileges(() =>
{
using (var site = new SPSite(url))
{
using (var web = site.OpenWeb())
{
if (web == null)
{
return;
}
Thread.CurrentThread.CurrentUICulture = new CultureInfo((int) web.Language);
bool condoAllowUnsafeUpdates = web.AllowUnsafeUpdates;
web.AllowUnsafeUpdates = true;
SPWeb boardWeb;
try
{
boardWeb = web.Webs.FirstOrDefault(w => w.Title.StartsWith("Hallitukselle"));
}
catch (Exception ex)
{
error("error occured when tring to get Hallitukselle web error: {0} {1}", ex.Message,
ex.StackTrace);
return;
}
if (boardWeb == null)
{
this.warn("Site '{0}' doesn't exist. It will be ignored", url);
return;
}
if (!PublishingWeb.IsPublishingWeb(boardWeb))
{
this.warn("Site '{0}' is not publishing web. It will be ignored", url);
return;
}
bool allowUnsafeUpdates = boardWeb.AllowUnsafeUpdates;
try
{
boardWeb.AllowUnsafeUpdates = true;
var pweb = PublishingWeb.GetPublishingWeb(boardWeb);
if (pweb == null || pweb.DefaultPage == null ||
string.IsNullOrEmpty(pweb.DefaultPage.ServerRelativeUrl))
{
this.warn("Publishing web of '{0}' is null. It will be ignored", url);
return;
}
updateNewsWebPart(boardWeb);
string handlerUrl = SPUrlUtility.CombineUrl(boardWeb.Url,
"_layouts/15/Taloyhtio/CondoAutomation/BoardMemberWebPartUpdateHandler.ashx");
string urlWithQuery = string.Format("{0}?condo={1}", handlerUrl, boardWeb.ServerRelativeUrl);
var request = (HttpWebRequest)WebRequest.Create(urlWithQuery);
request.Credentials = CredentialCache.DefaultNetworkCredentials;
var response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
this.error("Error occured during webparts update");
}
}
catch (Exception ex)
{
this.error("Error occured during updating of Condo :\n{0}\n{1}", ex.Message,
ex.StackTrace);
}
finally
{
boardWeb.AllowUnsafeUpdates = allowUnsafeUpdates;
web.AllowUnsafeUpdates = condoAllowUnsafeUpdates;
}
}
}
});
}
catch (Exception ex)
{
this.error("Error occured during updating of Condo :\n{0}\n{1}", ex.Message, ex.StackTrace);
}
}
private void updateNewsWebPart(SPWeb web)
{
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream(ResourceName))
{
if (stream != null)
using (var reader = new StreamReader(stream))
{
xslStyleSheet = reader.ReadToEnd();
}
}
var pweb = PublishingWeb.GetPublishingWeb(web);
xslStyleSheet = xslStyleSheet.Replace("~Site", web.ServerRelativeUrl);
try
{
var file = pweb.DefaultPage;
if (file == null)
{
this.error("Start page is null. Site won't be updated");
return;
}
if (file.CheckOutType == SPFile.SPCheckOutType.None)
{
file.CheckOut();
}
else
{
file.UndoCheckOut();
file.CheckOut();
}
SPLimitedWebPartManager webPartManager = null;
using (webPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
if (webPartManager == null)
{
this.error("Web part manager is null. Site won't be updated");
file.UndoCheckOut();
return;
}
bool changed = false;
var webParts = webPartManager.WebParts;
if (webParts != null)
{
foreach (WebPart wp in webParts)
{
if (wp.Title.Equals(TitleOld) || wp.Title.Equals(TitleOld2))
{
Hashtable wpdata = new Hashtable();
((DataFormWebPart)wp).GetParametersData(wpdata);
wp.Title = TitleNew;
Regex regex = new Regex("NewsList=(?<Id>([a-f0-9-]+))\"", RegexOptions.IgnoreCase);
Match match = regex.Match(((DataFormWebPart)wp).Xsl);
if (match.Success)
{
string listId = match.Groups["Id"].Value;
xslStyleSheet = xslStyleSheet.Replace("{ListId}", listId);
((DataFormWebPart)wp).Xsl = xslStyleSheet;
}
webPartManager.SaveChanges(wp);
changed = true;
break;
}
}
}
if (!changed)
{
file.UndoCheckOut();
return;
}
file.Update();
file.CheckIn("Updated 'hallituksille news' webpart");
file.Publish("Updated 'hallituksille news' webpart");
}
}
catch (Exception ex)
{
this.error("Error occured when update web part on '{0}' site:\n{1}\n{2}", pweb.Web.Url, ex.Message, ex.StackTrace);
var file = pweb.DefaultPage;
if (file.CheckOutType != SPFile.SPCheckOutType.None)
{
file.UndoCheckOut();
}
}
}
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 });
}
}
}
}