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

371 lines
15 KiB
C#

using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.WebPartPages;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.WebControls.WebParts;
using Taloyhtio.CondoUpdate.Common;
using WebPart = System.Web.UI.WebControls.WebParts.WebPart;
namespace CondoUpdate.ResponsiveLayout.CompanyDiscussionBoardWebPart
{
public class UpdaterImpl : ICondoUpdater
{
private const string ListTitle = "Keskustelu";
//private const string ListTitle = "Huomioitavaa ja kommentteja"; // for /tilitoimistoverso
private const string WebPartTitle = "Keskustelu";
//private const string WebPartTitle = "Huomioitavaa ja kommentteja"; // for /tilitoimistoverso
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)
{
try
{
using (var site = new SPSite(url))
{
using (var companyWeb = site.OpenWeb())
{
if (!companyWeb.Exists)
{
this.warn("Site '{0}' doesn't exist. It will be ignored", url);
return;
}
if (!PublishingWeb.IsPublishingWeb(companyWeb))
{
this.warn("Web '{0}' is not publishing. It will be ignored", url);
return;
}
Thread.CurrentThread.CurrentUICulture = new CultureInfo((int)companyWeb.Language);
bool condoAllowUnsafeUpdates = companyWeb.AllowUnsafeUpdates;
companyWeb.AllowUnsafeUpdates = true;
try
{
this.AddWebPart(companyWeb);
//this.LimitRow(companyWeb);
}
catch (Exception ex)
{
error("error occured when tring to get company web error: {0} {1}", ex.Message, ex.StackTrace);
}
finally
{
companyWeb.AllowUnsafeUpdates = condoAllowUnsafeUpdates;
}
}
}
}
catch (Exception ex)
{
error("error occured when tring to get company web error: {0} {1}", ex.Message, ex.StackTrace);
}
}
private void LimitRow(SPWeb web)
{
PublishingWeb pweb = null;
try
{
pweb = PublishingWeb.GetPublishingWeb(web);
if (pweb == null)
{
this.warn("publishing web is null, ignore");
return;
}
var file = pweb.DefaultPage;
if (file == null)
{
this.error("start page is null, exit");
return;
}
if (file.CheckOutType != SPFile.SPCheckOutType.None)
{
file.UndoCheckOut();
}
file.CheckOut();
bool changed = false;
using (var webpartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
if (webpartManager == null)
{
this.error("webpart manager is null, exit");
file.UndoCheckOut();
return;
}
foreach (WebPart wp in webpartManager.WebParts)
{
if (wp is XsltListViewWebPart && wp.Title.Equals(WebPartTitle))
{
var view = ((XsltListViewWebPart)wp).View;
view.RowLimit = 5;
view.Update();
changed = true;
break;
}
}
}
if (changed)
{
file.Update();
file.CheckIn("DiscussionBoardWebPart is added");
if (file.Item.ParentList.EnableMinorVersions)
{
file.Publish("DiscussionBoardWebPart is added");
}
if (file.Item.ParentList.EnableModeration)
{
file.Approve("DiscussionBoardWebPart is added");
}
}
else
{
file.UndoCheckOut();
}
}
catch (Exception x)
{
this.error("an error occured while modifying web part to the '{0}' site:\n{1}\n{2}", web.Url, x.Message, x.StackTrace);
if (pweb != null)
{
var file = pweb.DefaultPage;
if (file != null && file.CheckOutType != SPFile.SPCheckOutType.None)
{
file.UndoCheckOut();
}
}
}
}
private void AddWebPart(SPWeb web)
{
PublishingWeb pweb = null;
try
{
pweb = PublishingWeb.GetPublishingWeb(web);
if (pweb == null || pweb.DefaultPage == null ||
string.IsNullOrEmpty(pweb.DefaultPage.ServerRelativeUrl))
{
this.warn("Publishing web of '{0}' is null. It will be ignored", web.Url);
return;
}
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
{
// if file was checked out by another user, need undo check out and check in again in order to avoid errors
// when add web part
file.UndoCheckOut();
file.CheckOut();
}
using (var webPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
if (webPartManager == null)
{
this.error("Web part manager is null. Site won't be updated");
file.UndoCheckOut();
return;
}
var list = web.Lists.Cast<SPList>().FirstOrDefault(l => string.Equals(l.Title, ListTitle, StringComparison.InvariantCultureIgnoreCase));
if (list != null)
{
SPView view = list.DefaultView;
if (view != null)
{
if (!view.ViewFields.Exists("LinkDiscussionTitle"))
view.ViewFields.Add("LinkDiscussionTitle");
if (!view.ViewFields.Exists("Author"))
view.ViewFields.Add("Author");
if (!view.ViewFields.Exists("ItemChildCount"))
view.ViewFields.Add("ItemChildCount");
if (!view.ViewFields.Exists("Created"))
view.ViewFields.Add("Created");
if (!view.ViewFields.Exists("Body"))
view.ViewFields.Add("Body");
if (!view.ViewFields.Exists("LastReplyBy"))
view.ViewFields.Add("LastReplyBy");
if (!view.ViewFields.Exists("DiscussionLastUpdated"))
view.ViewFields.Add("DiscussionLastUpdated");
if (!view.ViewFields.Exists("BestAnswerId"))
view.ViewFields.Add("BestAnswerId");
if (!view.ViewFields.Exists("IsFeatured"))
view.ViewFields.Add("IsFeatured");
if (!view.ViewFields.Exists("LikesCount"))
view.ViewFields.Add("LikesCount");
if (!view.ViewFields.Exists("LikedBy"))
view.ViewFields.Add("LikedBy");
if (!view.ViewFields.Exists("Popularity"))
view.ViewFields.Add("Popularity");
if (!view.ViewFields.Exists("DescendantLikesCount"))
view.ViewFields.Add("DescendantLikesCount");
if (!view.ViewFields.Exists("DescendantRatingsCount"))
view.ViewFields.Add("DescendantRatingsCount");
if (!view.ViewFields.Exists("TopicLastRatedOrLikedBy"))
view.ViewFields.Add("TopicLastRatedOrLikedBy");
view.Update();
list.Update();
}
//bool alreadyExists = false;
var webParts = webPartManager.WebParts;
if (webParts != null)
{
if (webParts.Cast<WebPart>().Any(wp => wp.Title.ToLower().Equals(WebPartTitle.ToLower())))
{
var oldWebPart = webParts.Cast<WebPart>().First(wp => wp.Title.ToLower().Equals(WebPartTitle.ToLower()));
webPartManager.DeleteWebPart(oldWebPart);
}
/*if (webParts.Cast<WebPart>().Any(wp => wp.Title.ToLower().Equals(WebPartTitle.ToLower())))
{
this.warn("discussion board web part already exist on start page. Site won't be updated");
alreadyExists = true;
}*/
}
/*if (alreadyExists)
{
file.UndoCheckOut();
return;
}*/
if (view != null)
{
var xslt = new XsltListViewWebPart
{
Title = WebPartTitle,
ClientRender = true,
};
if (!string.IsNullOrEmpty(list.DefaultView.GetViewXml()))
{
xslt.XmlDefinition = list.DefaultView.GetViewXml();
}
if (list.ID != Guid.Empty)
{
xslt.ListId = list.ID;
}
if (!string.IsNullOrEmpty(list.DefaultViewUrl))
{
xslt.TitleUrl = list.DefaultViewUrl;
}
if (view.ID != Guid.Empty)
{
xslt.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();
}
if (!string.IsNullOrEmpty(list.DefaultView.BaseViewID))
{
xslt.ViewId = int.Parse(list.DefaultView.BaseViewID);
}
webPartManager.AddWebPart(xslt, "RightColumnZone", 2);
webPartManager.SaveChanges(xslt);
}
else
{
this.warn("Subject view is null. Site won't be updated");
file.UndoCheckOut();
return;
}
}
file.Update();
file.CheckIn("DiscussionBoardWebPart is added");
if (file.Item.ParentList.EnableMinorVersions)
{
file.Publish("DiscussionBoardWebPart is added");
}
if (file.Item.ParentList.EnableModeration)
{
file.Approve("DiscussionBoardWebPart is added");
}
}
}
catch (Exception x)
{
this.error("Error occured when add web part to the '{0}' site:\n{1}\n{2}", web.Url, x.Message, x.StackTrace);
if (pweb != null)
{
var file = pweb.DefaultPage;
if (file != null && file.CheckOutType != SPFile.SPCheckOutType.None)
{
file.UndoCheckOut();
}
}
}
}
#region notify
private void info(string msg, params object[] args)
{
this.notify(LogLevel.Info, msg, args);
}
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
}
}