using System; using System.Collections.Generic; using System.Linq; using Microsoft.SharePoint; using Microsoft.SharePoint.Publishing; using Taloyhtio.CondoUpdate.Common; namespace CondoUpdate.SetPermissionsForDomusPage { public class UpdaterImpl : ICondoUpdater { public event EventHandler OnNotify; public static List infos = null; 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) { if (infos == null) { var parser = new Parser(this); infos = parser.Parse("input.csv"); } if (infos.IsNullOrEmpty()) { this.warn("No users were found for condos. Update won't be done"); return; } if (!url.EndsWith("/")) url += "/"; var info = infos.FirstOrDefault(i => string.Compare(i.Url, url, true) == 0); if (info == null) { this.warn("User is not found for condo '{0}'. Update won't be done", url); return; } using (var site = new SPSite(url)) { using (var web = site.OpenWeb()) { var pweb = PublishingWeb.GetPublishingWeb(web); var page = pweb.GetPublishingPages().FirstOrDefault(p => string.Compare(p.Name, "tilintarkastus.aspx", true) == 0); if (page == null) { this.warn("Page Tilintarkastus.aspx not found on '{0}'", url); return; } var pmcRoleDefinition = web.RoleDefinitions.Cast().FirstOrDefault(r => r.Name == "Isännöitsijä"); if (pmcRoleDefinition == null) { this.error("Pmc role definition roleDefinition not found. Update won't be done"); return; } var pmcGroup = web.SiteGroups.Cast().FirstOrDefault(u => u.Name == string.Format("{0} - Isännöitsijät", web.Site.RootWeb.Title)); if (pmcGroup == null) { this.error("Pmc group not found. Update won't be done"); return; } string loginName = string.Format("taloyhtio:{0}", info.Username); var user = web.AllUsers.Cast().FirstOrDefault(u => string.Compare(u.LoginName, loginName, true) == 0); if (user == null) { this.error("User '{0}' not found. Update won't be done", info.Username); return; } var pmcRoleAssignment = new SPRoleAssignment(pmcGroup); SecurityHelper.AssignRoleToSecurableObject(web, page.ListItem, pmcRoleDefinition, pmcRoleAssignment, false); SecurityHelper.AssignUserRoleToSecurableObject(web, page.ListItem, SPRoleType.Reader, user); } } } public void info(string msg, params object[] args) { this.notify(LogLevel.Info, msg, args); } public void warn(string msg, params object[] args) { this.notify(LogLevel.Warn, msg, args); } public void error(string msg, params object[] args) { this.notify(LogLevel.Error, msg, args); } public 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 }); } } } }