using System; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Web.UI.WebControls.WebParts; using System.Xml; using Microsoft.SharePoint; using Microsoft.SharePoint.Publishing; using Microsoft.SharePoint.Utilities; using Microsoft.SharePoint.WebPartPages; using Taloyhtio.CondoAutomation.Resources; using Taloyhtio.CondoAutomation.Utils; using Taloyhtio.CondoUpdate.Common; using WebPart = System.Web.UI.WebControls.WebParts.WebPart; namespace CondoUpdate.AddCrossSitePressReleasesWebPart { public class UpdaterImpl : ICondoUpdater { 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(SPUrlUtility.CombineUrl(url, "Osakkaille")); } 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.OpenWeb()) { if (!web.Exists) { return; } Thread.CurrentThread.CurrentUICulture = new CultureInfo((int)web.Language); if (!PublishingWeb.IsPublishingWeb(web)) { return; } var psite = new PublishingSite(site); var pweb = PublishingWeb.GetPublishingWeb(web); var list = pweb.PagesList; bool newsPageExists = false; foreach (SPListItem item in list.Items) { string fileUrl = item.File.Url.ToLower(); if (fileUrl.EndsWith("/uutinen.aspx")) { newsPageExists = true; break; } } if (!newsPageExists) { var pageLayouts = psite.GetPageLayouts(false); var pageLayout = pageLayouts.FirstOrDefault(l => l.ServerRelativeUrl.ToLower().EndsWith("taloyhtio_responsive_layout.aspx")); if (pageLayout != null) { var page = pweb.AddPublishingPage("uutinen.aspx", pageLayout); var item = page.ListItem; item[SPBuiltInFieldId.Title] = SPUtility.GetLocalizedString("$Resources:Page_News_Title", "TaloyhtioLandlordsSite", web.Language); item[SPBuiltInFieldId.ContentType] = SPUtility.GetLocalizedString("$Resources:contenttype_welcomepage_name", "cmscore", web.Language); item.Update(); item.File.CheckIn("Create uutinen page"); if (item.ParentList.EnableMinorVersions) { item.File.Publish("Create uutinen page"); } } else { this.warn("Custom page layout taloyhtio_responsive_layout.aspx not found. Uutinen.aspx page won't be created"); } } foreach (SPListItem item in list.Items) { string fileUrl = item.File.Url.ToLower(); if (fileUrl.EndsWith("/default.aspx")) { this.addWebPart(pweb, item.File, "Isännöitsijältä osakkaille default.webpart", "Isännöitsijältä osakkaille", "LeftColumnZone", 0); this.fixWebPart(pweb, item.File); WebPartsHelper.SetupDataFormWebPartOnStartPage(pweb, TaloyhtioPropertyManagersSite.List_LandlordsReleases_Title, Constants.Retargeting.LANDLORDS_OLD_TARGET_LIST_ID_ON_START_PAGE, Constants.Retargeting.OLD_TARGET_WEB_URL); } } foreach (SPListItem item in list.Items) { string fileUrl = item.File.Url.ToLower(); if (fileUrl.EndsWith("/uutinen.aspx")) { this.addWebPart(pweb, item.File, "Kyselymerkkijonon uutinen.webpart", "Kyselymerkkijonon (URL) suodatin", "LeftColumnZone", 0); this.addWebPart(pweb, item.File, "Osakastiedotteet uutinen.webpart", "Osakastiedotteet", "TopColumnZone", 0); this.fixWebPart(pweb, item.File); this.addWebPart(pweb, item.File, "Liitteet uutinen.webpart", "Liitteet", "TopColumnZone", 1); WebPartsHelper.SetupWebPartsOnNewsPage(pweb, TaloyhtioLandlordsSite.Page_News_Title, TaloyhtioPropertyManagersSite.List_LandlordsReleases_Title, Constants.Retargeting.OLD_TARGET_LIST_ID_ON_NEWS_PAGE, Constants.Retargeting.OLD_TARGET_WEB_URL); } } pweb.ExcludeFromNavigation(true, TaloyhtioBoardMembersSite.Page_News_Title); } } } private void addWebPart(PublishingWeb pweb, SPFile file, string wpFile, string wpTitle, string webPartZone, int index) { SPLimitedWebPartManager webPartManager = null; try { if (file.CheckOutStatus == SPFile.SPCheckOutStatus.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(); } webPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared); if (webPartManager == null) { this.error("Web part manager is null. Site won't be updated"); file.UndoCheckOut(); return; } var webParts = webPartManager.WebParts; if (webParts == null) { file.UndoCheckOut(); return; } foreach (WebPart wp in webParts) { if (wp.Title == wpTitle) { file.UndoCheckOut(); return; } } using (var fs = new MemoryStream(Encoding.UTF8.GetBytes(File.ReadAllText(wpFile)))) { using (var reader = new XmlTextReader(fs)) { string error; WebPart wp = webPartManager.ImportWebPart(reader, out error); if (wp == null) { this.error("Imported web part is null. Site '{0}' won't be updated. Error message: {1}", pweb.Web.Url, error); file.UndoCheckOut(); return; } webPartManager.AddWebPart(wp, webPartZone, index); webPartManager.SaveChanges(wp); } } file.CheckIn("Web part is added"); file.Update(); file.Publish("Web part is added"); } catch (Exception x) { this.error("Error occured when add web part to the '{0}' site:\n{1}\n{2}", pweb.Web.Url, x.Message, x.StackTrace); if (file.CheckOutStatus != SPFile.SPCheckOutStatus.None) { file.UndoCheckOut(); } } finally { if (webPartManager != null) { if (webPartManager.Web != null) { webPartManager.Web.Dispose(); } webPartManager.Dispose(); } } } private void fixWebPart(PublishingWeb pweb, SPFile file) { SPLimitedWebPartManager webPartManager = null; try { //this.info("Get start page"); if (file.CheckOutStatus == SPFile.SPCheckOutStatus.None) { //this.info("Checkout start page"); 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 //this.info("Start page is already checked out. Undo previous check out and check out it again"); file.UndoCheckOut(); file.CheckOut(); } //this.info("Get web part manager"); webPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared); if (webPartManager == null) { this.error("Web part manager is null. Site won't be updated"); file.UndoCheckOut(); return; } //this.info("Search for DataFormWebPart with title '{0}' on the start page", webPartTitle); Microsoft.SharePoint.WebPartPages.DataFormWebPart webPart = null; var webParts = webPartManager.WebParts; if (webParts != null) { foreach (WebPart wp in webParts) { if (wp.GetType().FullName == "Microsoft.SharePoint.WebPartPages.DataFormWebPart") { webPart = wp as Microsoft.SharePoint.WebPartPages.DataFormWebPart; break; } } } if (webPart == null) { this.warn("DataFormWebPart not found. It won't be updated"); file.UndoCheckOut(); return; } //this.info("DataFormWebPart '{0}' found on the start page", webPartTitle); //if (!webPart.Xsl.Contains("href=\"~SiteCollection/Lists/Hallitustiedotteet/AllItems.aspx\"")) var re = new Regex("href=\"~Site/_layouts/15/taloyhtio/condoautomation/ownersnews.aspx\""); var m = re.Match(webPart.Xsl); if (!m.Success) { this.warn("Link to list view not found in web part's xsl"); file.UndoCheckOut(); return; } //this.info("DataSourcesString property contains SelectCommand"); webPart.Xsl = re.Replace(webPart.Xsl, string.Format("href=\"{0}\"", SPUrlUtility.CombineUrl(pweb.Web.ServerRelativeUrl, "/_layouts/15/taloyhtio/condoautomation/ownersnews.aspx"))); webPartManager.SaveChanges(webPart); //this.info("DataSourcesString property of web part '{0}' was sucessfully updated", webPartTitle); //this.info("Checkin file"); file.Update(); file.CheckIn("Change arkisto link"); if (file.Item.ParentList.EnableMinorVersions) { file.Publish("Change arkisto link"); } //this.info("Web part was sucessfully updated"); } catch (Exception x) { this.error("Error occured when update web part on '{0}' site:\n{1}\n{2}", pweb.Web.Url, x.Message, x.StackTrace); if (file.CheckOutStatus != SPFile.SPCheckOutStatus.None) { file.UndoCheckOut(); } } finally { if (webPartManager != null) { if (webPartManager.Web != null) { webPartManager.Web.Dispose(); } webPartManager.Dispose(); } } } 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 }); } } } }