using System; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Web; using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using Microsoft.SharePoint.Utilities; using Taloyhtio.CondoUpdate.Common; namespace CondoUpdate.AddSiteCollectionAdmin { 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(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) { SPSecurity.RunWithElevatedPrivileges( () => { using (var siteDefault = new SPSite(url)) { using (var site = new SPSite(siteDefault.ID, SPUrlZone.Extranet)) { using (var web = site.OpenWeb()) { //this.info("Web url is '{0}'", web.Url); web.AllowUnsafeUpdates = true; HttpRequest request = new HttpRequest("", web.Url, ""); HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter())); HttpContext.Current.Items["HttpHandlerSPWeb"] = web; string key = "userToSiteCollectionAdmin"; string userName = ConfigurationManager.AppSettings[key]; if (string.IsNullOrEmpty(userName)) { this.error("User name is not specified in '{0}' app setting", key); return; } var user = web.EnsureUser(userName); if (user == null) { this.error("User not found for site '{0}'", site.Url); return; } if (user.IsSiteAdmin) { this.info(""); return; } user.IsSiteAdmin = true; user.Update(); HttpContext.Current.Items["HttpHandlerSPWeb"] = null; HttpContext.Current = null; } } } }); } 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 }); } } } }