private static void SetCustomActionResourceValues(TokenParser parser, CustomAction customAction, UserCustomAction uca) { if (uca != null) { bool isDirty = false; #if !ONPREMISES if (!string.IsNullOrEmpty(customAction.Title) && customAction.Title.ContainsResourceToken()) { if (uca.TitleResource.SetUserResourceValue(customAction.Title, parser)) { isDirty = true; } } if (!string.IsNullOrEmpty(customAction.Description) && customAction.Description.ContainsResourceToken()) { if (uca.DescriptionResource.SetUserResourceValue(customAction.Description, parser)) { isDirty = true; } } #endif if (isDirty) { uca.Update(); uca.Context.ExecuteQueryRetry(); } } }
public static void AddorRemoveCustomAction(ClientContext ctx, Uri appUrl, string custactionType) { List list = ctx.Web.GetListByTitle("Customer List"); if (custactionType == "Remove") { ctx.Load(list.UserCustomActions); ctx.ExecuteQuery(); int customActions = list.UserCustomActions.Count(); for (int i = customActions; i > 0; i--) { if (list.UserCustomActions[i - 1].Name == "CustomName") { list.UserCustomActions[i - 1].DeleteObject(); ctx.ExecuteQuery(); } } } else { UserCustomAction action = list.UserCustomActions.Add(); action.Title = "Go to Customer Card"; action.Name = "CustomName"; action.Url = appUrl.Scheme + "://" + appUrl.Authority + "/CustomerCard/Index" + appUrl.Query + "&ListId={ListId}&ListItemId={ItemId}"; action.Location = "EditControlBlock"; action.Sequence = 1; action.Update(); ctx.ExecuteQuery(); } }
public static void AddCustomAction(List list, string actionUrl) { ClientContext context = (ClientContext)list.Context; context.Load(list.UserCustomActions); context.ExecuteQuery(); foreach (UserCustomAction uca in list.UserCustomActions) { uca.DeleteObject(); } context.ExecuteQuery(); UserCustomAction action = list.UserCustomActions.Add(); action.Location = "EditControlBlock"; action.Sequence = 10001; action.Title = "Publish this Lessons Learned"; var permissions = new BasePermissions(); permissions.Set(PermissionKind.EditListItems); action.Rights = permissions; action.Url = actionUrl; action.Update(); context.ExecuteQuery(); }
/// <summary> /// Adds or Updates an existing Custom Action [Url] into the [List] Custom Actions /// </summary> /// <param name="list"></param> /// <param name="customactionname"></param> /// <param name="commandUIExtension"></param> public static void AddOrUpdateCustomActionLink(this List list, string customactionname, string commandUIExtension, string location, int sequence) { var sitecustomActions = list.UserCustomActions; list.Context.Load(sitecustomActions); list.Context.ExecuteQueryRetry(); UserCustomAction cssAction = null; if (sitecustomActions.Any(sa => sa.Name == customactionname)) { cssAction = sitecustomActions.FirstOrDefault(fod => fod.Name == customactionname); } else { // Build a custom action cssAction = sitecustomActions.Add(); cssAction.Name = customactionname; } cssAction.Sequence = sequence; cssAction.Location = location; cssAction.CommandUIExtension = commandUIExtension; cssAction.Update(); list.Context.ExecuteQueryRetry(); }
private void WireUpJSFileInternal(string scriptSource, string actionName, int sequence) { UserCustomActionCollection userCustomActions = GetCurrentUserCustomActionsDeclaredOnThisWeb(); bool alreadyPresent = false; foreach (UserCustomAction userCustomAction in userCustomActions) { if (!string.IsNullOrEmpty(userCustomAction.Name) && userCustomAction.Name == actionName) { alreadyPresent = true; break; } } if (!alreadyPresent) { // add it UserCustomAction action = userCustomActions.Add(); action.ScriptSrc = scriptSource; action.Location = "ScriptLink"; action.Name = actionName; action.Sequence = sequence; action.Update(); this.hostWebClientContextField.ExecuteQuery(); } }
public static void AddAddBirthdayAction(ClientContext ctx) { if (!ctx.Web.ListExists("Person")) { ctx.Web.CreateList(ListTemplateType.GenericList, "Person", false); } List list = ctx.Web.GetListByTitle("Person"); if (!list.FieldExistsById("{A7A83D5A-06C4-4EA0-94D4-831B74B2E077}")) { FieldCreationInformation fieldInfo = new FieldCreationInformation(FieldType.Number); fieldInfo.Id = "{A7A83D5A-06C4-4EA0-94D4-831B74B2E077}".ToGuid(); fieldInfo.InternalName = "CUSTOM_AGE"; fieldInfo.DisplayName = "Current Age"; list.CreateField(fieldInfo); } DelectCustomActionFromList(ctx, "AddAge", list); ctx.Load(ctx.Web, w => w.Url); ctx.ExecuteQuery(); UserCustomAction customAction = list.UserCustomActions.Add(); customAction.Name = "AddAge"; customAction.Location = "EditControlBlock"; customAction.Title = "Have birthday"; customAction.Url = "javascript:window.location = 'https://localhost:44363/home/HaveBirthday?SPHostUrl=" + ctx.Web.Url + "&listId={ListId}&itemid={ItemId}'"; customAction.Update(); ctx.ExecuteQuery(); }
protected void btnScenario1_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { Web web = clientContext.Web; List assetLibrary = web.Lists.GetByTitle("Site Assets"); clientContext.Load(assetLibrary, l => l.RootFolder); // Get the path to the file which we are about to deploy string file = System.Web.Hosting.HostingEnvironment.MapPath(string.Format("~/{0}", "CSS/contoso.css")); // Use CSOM to uplaod the file in FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(file); newFile.Url = "contoso.css"; newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = assetLibrary.RootFolder.Files.Add(newFile); clientContext.Load(uploadFile); clientContext.ExecuteQuery(); // Now, apply a reference to the CSS URL via a custom action string actionName = "ContosoCSSLink"; // Clean up existing actions that we may have deployed var existingActions = web.UserCustomActions; clientContext.Load(existingActions); // Execute our uploads and initialzie the existingActions collection clientContext.ExecuteQuery(); // Clean up existing custom action with same name, if it exists foreach (var existingAction in existingActions) { if (existingAction.Name.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)) { existingAction.DeleteObject(); } } clientContext.ExecuteQuery(); // Build a custom action to write a link to our new CSS file UserCustomAction cssAction = web.UserCustomActions.Add(); cssAction.Location = "ScriptLink"; cssAction.Sequence = 100; cssAction.ScriptBlock = @"document.write('<link rel=""stylesheet"" href=""" + assetLibrary.RootFolder.ServerRelativeUrl + @"/contoso.css"" />');"; cssAction.Name = actionName; // Apply cssAction.Update(); clientContext.ExecuteQuery(); } } }
public static void ProvisionArtifactsByCode() { // Create a PnP AuthenticationManager object AuthenticationManager am = new AuthenticationManager(); // Authenticate against SPO with an App-Only access token using (ClientContext context = am.GetAzureADAppOnlyAuthenticatedContext( O365ProjectsAppContext.CurrentSiteUrl, O365ProjectsAppSettings.ClientId, O365ProjectsAppSettings.TenantId, O365ProjectsAppSettings.AppOnlyCertificate)) { Web web = context.Web; List targetLibrary = null; // If the target library does not exist (PnP extension method) if (!web.ListExists(O365ProjectsAppSettings.LibraryTitle)) { // Create it using another PnP extension method targetLibrary = web.CreateList(ListTemplateType.DocumentLibrary, O365ProjectsAppSettings.LibraryTitle, true, true); } else { targetLibrary = web.GetListByTitle(O365ProjectsAppSettings.LibraryTitle); } // If the target library exists if (targetLibrary != null) { // Try to get the user's custom action UserCustomAction customAction = targetLibrary.GetCustomAction(O365ProjectsAppConstants.ECB_Menu_Name); // If it doesn't exist if (customAction == null) { // Add the user custom action to the list customAction = targetLibrary.UserCustomActions.Add(); customAction.Name = O365ProjectsAppConstants.ECB_Menu_Name; customAction.Location = "EditControlBlock"; customAction.Sequence = 100; customAction.Title = "Manage Business Project"; customAction.Url = $"{O365ProjectsAppContext.CurrentAppSiteUrl}Project/?SiteUrl={{SiteUrl}}&ListId={{ListId}}&ItemId={{ItemId}}&ItemUrl={{ItemUrl}}"; } else { // Update the already existing Custom Action customAction.Name = O365ProjectsAppConstants.ECB_Menu_Name; customAction.Location = "EditControlBlock"; customAction.Sequence = 100; customAction.Title = "Manage Business Project"; customAction.Url = $"{O365ProjectsAppContext.CurrentAppSiteUrl}Project/?SiteUrl={{SiteUrl}}&ListId={{ListId}}&ItemId={{ItemId}}&ItemUrl={{ItemUrl}}"; } customAction.Update(); context.ExecuteQueryRetry(); } } }
public void Update() { if (_hasChanges) { _userCustomAction.Update(); _userCustomAction.Context.Load(_userCustomAction); _userCustomAction.Context.ExecuteQuery(); _hasChanges = false; } }
private void AddJsLink(Microsoft.SharePoint.Client.ClientContext ctx) { Web web = ctx.Web; ctx.Load(web, w => w.UserCustomActions); ctx.ExecuteQuery(); ctx.Load(web, w => w.UserCustomActions, w => w.Url, w => w.AppInstanceId); ctx.ExecuteQuery(); UserCustomAction userCustomAction = web.UserCustomActions.Add(); userCustomAction.Location = "Microsoft.SharePoint.StandardMenu"; userCustomAction.Group = "SiteActions"; BasePermissions perms = new BasePermissions(); perms.Set(PermissionKind.ManageWeb); userCustomAction.Rights = perms; userCustomAction.Sequence = 100; userCustomAction.Title = "Modify Site"; string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(ctx.Url)); string issuerId = WebConfigurationManager.AppSettings.Get("ClientId"); var modifyPageUrl = string.Format("https://{0}/Pages/Modify.aspx?{{StandardTokens}}", Request.Url.Authority); string url = "javascript:LaunchApp('{0}', 'i:0i.t|ms.sp.ext|{1}@{2}','{3}',{{width:300,height:200,title:'Modify Site'}});"; url = string.Format(url, Guid.NewGuid().ToString(), issuerId, realm, modifyPageUrl); userCustomAction.Url = url; userCustomAction.Update(); ctx.ExecuteQuery(); // Remove the entry from the 'Recents' node NavigationNodeCollection nodes = web.Navigation.QuickLaunch; ctx.Load(nodes, n => n.IncludeWithDefaultProperties(c => c.Children)); ctx.ExecuteQuery(); var recent = nodes.Where(x => x.Title == "Recent").FirstOrDefault(); if (recent != null) { var appLink = recent.Children.Where(x => x.Title == "Site Modifier").FirstOrDefault(); if (appLink != null) { appLink.DeleteObject(); } ctx.ExecuteQuery(); } }
/// <summary> /// Handler for teh JS injection pattern /// </summary> /// <param name="clientContext"> /// </param> private void AddJSInjectionToSite(ClientContext clientContext) { // Add JS file to web remotely this.DeployJSInjectionFilesToContextWeb(clientContext); if (!this.CustomActionForJSInjectionAlreadyExists(clientContext)) { UserCustomAction action = clientContext.Web.UserCustomActions.Add(); action.ScriptSrc = "~site/Injection_JS/SubSiteRemoteProvisioningWeb_InjectedJS.js"; action.Location = "ScriptLink"; action.Name = "Injection_JS"; action.Sequence = 1000; action.Update(); clientContext.ExecuteQuery(); } }
/// <summary> /// </summary> private void AddScript(ClientContext ctx, Site site, Web web, ref UserActionObject ucaObj) { UserCustomAction uca = null; if (scope.IsEqual("Site Collection")) { uca = site.UserCustomActions.Add(); } else { uca = web.UserCustomActions.Add(); } uca.Location = "ScriptLink"; if (!ucaObj.scriptSrc.IsNull()) { uca.ScriptSrc = ucaObj.scriptSrc; } if (!ucaObj.scriptBlock.IsNull()) { uca.ScriptBlock = ucaObj.scriptBlock; } if (!ucaObj.descr.IsNull()) { uca.Description = ucaObj.descr; } if (!ucaObj.name.IsNull()) { uca.Title = uca.Name = ucaObj.name; } uca.Sequence = ucaObj.seq; uca.Update(); ctx.Load(uca, x => x.Id, x => x.Name); ctx.ExecuteQuery(); ucaObj.id = uca.Id.ToString(); tcout("Action added", ucaObj.id); }
private void AddSiteInformationJsLink(Microsoft.SharePoint.Client.ClientContext clientContext) { Web web = clientContext.Web; clientContext.Load(web, w => w.UserCustomActions, w => w.Url, w => w.AppInstanceId); clientContext.ExecuteQuery(); string issuerId = ConfigurationManager.AppSettings.Get("ClientId"); DeleteExistingActions(clientContext, web); UserCustomAction userCustomAction = web.UserCustomActions.Add(); userCustomAction.Location = "Microsoft.SharePoint.StandardMenu"; userCustomAction.Group = "SiteActions"; BasePermissions perms = new BasePermissions(); perms.Set(PermissionKind.ManageWeb); userCustomAction.Rights = perms; userCustomAction.Sequence = 100; userCustomAction.Title = "Site Information"; userCustomAction.Name = "SiteInformationApp"; string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(clientContext.Url)); string host = ""; foreach (Uri u in OperationContext.Current.Host.BaseAddresses) { if (u.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase)) { host = u.Authority; } } var appPageUrl = string.Format("https://{0}/Pages/Default.aspx?{{StandardTokens}}", host); string url = "javascript:LaunchApp('{0}', 'i:0i.t|ms.sp.ext|{1}@{2}','{3}', {{width:600,height:400,title:'Site Information'}});"; url = string.Format(url, Guid.NewGuid().ToString(), issuerId, realm, appPageUrl); userCustomAction.Url = url; userCustomAction.Update(); clientContext.ExecuteQuery(); }
public void AddJsLink(Microsoft.SharePoint.Client.ClientContext ctx) { Web web = ctx.Web; ctx.Load(web, w => w.UserCustomActions); ctx.ExecuteQuery(); ctx.Load(web, w => w.UserCustomActions, w => w.Url, w => w.AppInstanceId); ctx.ExecuteQuery(); UserCustomAction userCustomAction = web.UserCustomActions.Add(); userCustomAction.Location = "Microsoft.SharePoint.StandardMenu"; userCustomAction.Group = "SiteActions"; BasePermissions perms = new BasePermissions(); perms.Set(PermissionKind.ManageWeb); userCustomAction.Rights = perms; userCustomAction.Sequence = 100; userCustomAction.Title = "Say Hello"; string url = "javascript:alert('Hello SharePoint Custom Action!!!');"; userCustomAction.Url = url; userCustomAction.Update(); ctx.ExecuteQuery(); // Remove the entry from the 'Recents' node Microsoft.SharePoint.Client.NavigationNodeCollection nodes = web.Navigation.QuickLaunch; ctx.Load(nodes, n => n.IncludeWithDefaultProperties(c => c.Children)); ctx.ExecuteQuery(); var recent = nodes.Where(x => x.Title == "Recent").FirstOrDefault(); if (recent != null) { var appLink = recent.Children.Where(x => x.Title == "Site Modifier").FirstOrDefault(); if (appLink != null) { appLink.DeleteObject(); } ctx.ExecuteQuery(); } }
static void Main(string[] args) { using (ClientContext ctx = LogInAsUser()) { //TaxonomyHelper.CreateTaxonomyFavColor(ctx); //SetupHelper.SetUp(ctx); ctx.Load(ctx.Web, w => w.Url); ctx.ExecuteQuery(); UserCustomAction action = ctx.Web.GetListByTitle("Schools").UserCustomActions.Add();; string url = "https://localhost:44358/"; action.Location = "EditControlBlock"; action.Sequence = 1; action.Name = "SchoolAction"; action.Title = "school card"; action.Url = "https://localhost:44358/Home/School?itemId={ItemId}&SPHostUrl=" + ctx.Web.Url; action.Update(); ctx.ExecuteQuery(); } }
/// <summary> /// Adds or Updates an existing Custom Action [ScriptBlock] into the [Site] Custom Actions /// </summary> /// <param name="site"></param> /// <param name="customactionname"></param> /// <param name="customActionBlock"></param> /// <param name="sequence"></param> public static void AddOrUpdateCustomActionLinkBlock(this Site site, string customactionname, string customActionBlock, int sequence) { var sitecustomActions = site.GetCustomActions(); UserCustomAction cssAction = null; if (site.CustomActionExists(customactionname)) { cssAction = sitecustomActions.FirstOrDefault(fod => fod.Name == customactionname); } else { // Build a custom action to write a link to our new CSS file cssAction = site.UserCustomActions.Add(); cssAction.Name = customactionname; cssAction.Location = "ScriptLink"; } cssAction.Sequence = sequence; cssAction.ScriptBlock = customActionBlock; cssAction.Update(); site.Context.ExecuteQueryRetry(); }
static void CreateScriptLinks() { // Register ScriptLink for jQuery UserCustomAction customAction1 = site.UserCustomActions.Add(); customAction1.Title = "jQuery"; customAction1.Location = "ScriptLink"; customAction1.ScriptSrc = "~SiteCollection/CPT/scripts/jquery.js"; customAction1.Sequence = 10; customAction1.Update(); // Register ScriptLink for custom javascript file UserCustomAction customAction2 = site.UserCustomActions.Add(); customAction2.Title = "CustomUserActions"; customAction2.Location = "ScriptLink"; customAction2.ScriptSrc = "~SiteCollection/CPT/scripts/CustomUserActions.js"; customAction2.Sequence = 11; customAction2.Update(); clientContext.ExecuteQuery(); }
/// <summary> /// Generic handler for custom action entries /// </summary> /// <param name="clientContext"> /// The client context /// </param> /// <param name="siteTemplate"> /// XML structure for the template /// </param> private void DeployCustomActions(ClientContext clientContext, XElement siteTemplate) { XElement customActionsToDeploy = siteTemplate.Element("CustomActions"); if (customActionsToDeploy != null) { foreach (XElement customAction in customActionsToDeploy.Elements()) { if (this.CustomActionAlreadyExists(clientContext, customAction.Attribute("Name").Value)) { continue; } UserCustomAction action = clientContext.Web.UserCustomActions.Add(); action.ScriptSrc = customAction.Attribute("ScriptSrc").Value; action.Location = customAction.Attribute("Location").Value; action.Name = customAction.Attribute("Name").Value; action.Sequence = 1000; action.Update(); clientContext.ExecuteQuery(); } } }
public static void AddCustomActionToListItem(ClientContext ctx) { if (!ctx.Web.ListExists("FakeList")) { ctx.Web.CreateList(ListTemplateType.GenericList, "FakeList", false); } List list = ctx.Web.GetListByTitle("FakeList"); DelectCustomActionFromList(ctx, "FakeCustomAction", list); ctx.Load(ctx.Web, w => w.Url); ctx.ExecuteQuery(); UserCustomAction userAction = list.UserCustomActions.Add(); userAction.Name = "FakeCustomAction"; userAction.Location = "EditControlBlock"; userAction.Title = "Fake Custom Action"; userAction.Url = "https://localhost:44363/home/about?SPHostUrl=" + ctx.Web.Url + "&listId={ListId}&itemid={ItemId}"; userAction.Update(); ctx.ExecuteQuery(); }
/// <summary> /// </summary> private void AddScript(ClientContext ctx, Site site, ref UserActionObject userActionObj) { UserCustomAction spUserCustomAction = site.UserCustomActions.Add(); spUserCustomAction.Location = "ScriptLink"; if (!userActionObj.scriptSrc.IsNull()) { spUserCustomAction.ScriptSrc = userActionObj.scriptSrc; } if (!userActionObj.scriptBlock.IsNull()) { spUserCustomAction.ScriptBlock = userActionObj.scriptBlock; } if (!userActionObj.descr.IsNull()) { spUserCustomAction.Description = userActionObj.descr; } if (!userActionObj.name.IsNull()) { spUserCustomAction.Name = userActionObj.name; } spUserCustomAction.Sequence = userActionObj.seq; spUserCustomAction.Update(); ctx.Load(spUserCustomAction, x => x.Id, x => x.Name); ctx.ExecuteQuery(); userActionObj.id = spUserCustomAction.Id.ToString(); tcout("Action added", userActionObj.id); }
/// <summary> /// Adds or Updates an existing Custom Action [Url] into the [List] Custom Actions /// </summary> /// <param name="list"></param> /// <param name="customactionname"></param> /// <param name="customactionurl"></param> /// <param name="title"></param> /// <param name="description"></param> /// <param name="location"></param> /// <param name="sequence">(default) 10000</param> /// <param name="groupName">(optional) adds custom group</param> public static void AddOrUpdateCustomActionLink(this List list, SPCustomActionList action) { var sitecustomActions = list.UserCustomActions; list.Context.Load(sitecustomActions); list.Context.ExecuteQueryRetry(); UserCustomAction cssAction = null; if (sitecustomActions.Any(sa => sa.Name == action.name)) { cssAction = sitecustomActions.FirstOrDefault(fod => fod.Name == action.name); } else { // Build a custom action cssAction = sitecustomActions.Add(); cssAction.Name = action.name; } cssAction.Sequence = action.sequence; cssAction.Url = action.Url; cssAction.Description = action.Description; cssAction.Location = action.Location; cssAction.Title = action.Title; if (!string.IsNullOrEmpty(action.ImageUrl)) { cssAction.ImageUrl = action.ImageUrl; } if (!string.IsNullOrEmpty(action.Group)) { cssAction.Group = action.Group; } cssAction.Update(); list.Context.ExecuteQueryRetry(); }
private void ProvisionCustomActionImplementation(object parent, List <CustomAction> customActions, TokenParser parser, PnPMonitoredScope scope) { Web web = null; Site site = null; if (parent is Site) { site = parent as Site; // Switch parser context; parser.Rebase(site.RootWeb); } else { web = parent as Web; // Switch parser context parser.Rebase(web); } foreach (var customAction in customActions) { var caExists = false; if (site != null) { caExists = site.CustomActionExists(customAction.Name); } else { caExists = web.CustomActionExists(customAction.Name); } if (!caExists) { var customActionEntity = new CustomActionEntity() { CommandUIExtension = customAction.CommandUIExtension != null?parser.ParseString(customAction.CommandUIExtension.ToString()) : string.Empty, Description = customAction.Description, Group = customAction.Group, ImageUrl = parser.ParseString(customAction.ImageUrl), Location = customAction.Location, Name = customAction.Name, RegistrationId = customAction.RegistrationId, RegistrationType = customAction.RegistrationType, Remove = customAction.Remove, Rights = customAction.Rights, ScriptBlock = parser.ParseString(customAction.ScriptBlock), ScriptSrc = parser.ParseString(customAction.ScriptSrc, "~site", "~sitecollection"), Sequence = customAction.Sequence, Title = customAction.Title, Url = parser.ParseString(customAction.Url) }; if (site != null) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_CustomActions_Adding_custom_action___0___to_scope_Site, customActionEntity.Name); site.AddCustomAction(customActionEntity); } else { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_CustomActions_Adding_custom_action___0___to_scope_Web, customActionEntity.Name); web.AddCustomAction(customActionEntity); } } else { UserCustomAction existingCustomAction = null; if (site != null) { existingCustomAction = site.GetCustomActions().FirstOrDefault(c => c.Name == customAction.Name); } else { existingCustomAction = web.GetCustomActions().FirstOrDefault(c => c.Name == customAction.Name); } if (existingCustomAction != null) { var isDirty = false; if (customAction.CommandUIExtension != null) { if (existingCustomAction.CommandUIExtension != parser.ParseString(customAction.CommandUIExtension.ToString())) { scope.LogPropertyUpdate("CommandUIExtension"); existingCustomAction.CommandUIExtension = parser.ParseString(customAction.CommandUIExtension.ToString()); isDirty = true; } } if (existingCustomAction.Description != customAction.Description) { scope.LogPropertyUpdate("Description"); existingCustomAction.Description = customAction.Description; isDirty = true; } if (existingCustomAction.Group != customAction.Group) { scope.LogPropertyUpdate("Group"); existingCustomAction.Group = customAction.Group; isDirty = true; } if (existingCustomAction.ImageUrl != parser.ParseString(customAction.ImageUrl)) { scope.LogPropertyUpdate("ImageUrl"); existingCustomAction.ImageUrl = parser.ParseString(customAction.ImageUrl); isDirty = true; } if (existingCustomAction.Location != customAction.Location) { scope.LogPropertyUpdate("Location"); existingCustomAction.Location = customAction.Location; isDirty = true; } if (existingCustomAction.RegistrationId != customAction.RegistrationId) { scope.LogPropertyUpdate("RegistrationId"); existingCustomAction.RegistrationId = customAction.RegistrationId; isDirty = true; } if (existingCustomAction.RegistrationType != customAction.RegistrationType) { scope.LogPropertyUpdate("RegistrationType"); existingCustomAction.RegistrationType = customAction.RegistrationType; isDirty = true; } if (existingCustomAction.ScriptBlock != parser.ParseString(customAction.ScriptBlock)) { scope.LogPropertyUpdate("ScriptBlock"); existingCustomAction.ScriptBlock = parser.ParseString(customAction.ScriptBlock); isDirty = true; } if (existingCustomAction.ScriptSrc != parser.ParseString(customAction.ScriptSrc, "~site", "~sitecollection")) { scope.LogPropertyUpdate("ScriptSrc"); existingCustomAction.ScriptSrc = parser.ParseString(customAction.ScriptSrc, "~site", "~sitecollection"); isDirty = true; } if (existingCustomAction.Title != parser.ParseString(customAction.Title)) { scope.LogPropertyUpdate("Title"); existingCustomAction.Title = parser.ParseString(customAction.Title); isDirty = true; } if (existingCustomAction.Url != parser.ParseString(customAction.Url)) { scope.LogPropertyUpdate("Url"); existingCustomAction.Url = parser.ParseString(customAction.Url); isDirty = true; } if (isDirty) { existingCustomAction.Update(); existingCustomAction.Context.ExecuteQueryRetry(); } } } } }
private static bool AddCustomActionImplementation(ClientObject clientObject, CustomActionEntity customAction) { UserCustomAction targetAction = null; UserCustomActionCollection existingActions = null; if (clientObject is Web) { var web = (Web)clientObject; existingActions = web.UserCustomActions; web.Context.Load(existingActions); web.Context.ExecuteQueryRetry(); targetAction = web.UserCustomActions.FirstOrDefault(uca => uca.Name == customAction.Name); } else { var site = (Site)clientObject; existingActions = site.UserCustomActions; site.Context.Load(existingActions); site.Context.ExecuteQueryRetry(); targetAction = site.UserCustomActions.FirstOrDefault(uca => uca.Name == customAction.Name); } if (targetAction == null) { // If we're removing the custom action then we need to leave when not found...else we're creating the custom action if (customAction.Remove) { return(true); } else { targetAction = existingActions.Add(); } } else if (customAction.Remove) { targetAction.DeleteObject(); clientObject.Context.ExecuteQueryRetry(); return(true); } targetAction.Name = customAction.Name; targetAction.Description = customAction.Description; targetAction.Location = customAction.Location; if (customAction.Location == JavaScriptExtensions.SCRIPT_LOCATION) { targetAction.ScriptBlock = customAction.ScriptBlock; targetAction.ScriptSrc = customAction.ScriptSrc; } else { targetAction.Sequence = customAction.Sequence; targetAction.Url = customAction.Url; targetAction.Group = customAction.Group; targetAction.Title = customAction.Title; targetAction.ImageUrl = customAction.ImageUrl; if (customAction.RegistrationId != null) { targetAction.RegistrationId = customAction.RegistrationId; } if (customAction.CommandUIExtension != null) { targetAction.CommandUIExtension = customAction.CommandUIExtension; } if (customAction.Rights != null) { targetAction.Rights = customAction.Rights; } if (customAction.RegistrationType.HasValue) { targetAction.RegistrationType = customAction.RegistrationType.Value; } } targetAction.Update(); if (clientObject is Web) { var web = (Web)clientObject; web.Context.Load(web, w => w.UserCustomActions); web.Context.ExecuteQueryRetry(); } else { var site = (Site)clientObject; site.Context.Load(site, s => s.UserCustomActions); site.Context.ExecuteQueryRetry(); } return(true); }
/// <summary> /// Handles app events that occur after the app is installed or upgraded, or when app is being uninstalled. /// </summary> /// <param name="properties">Holds information about the app event.</param> /// <returns>Holds information returned from the app event.</returns> public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties) { SPRemoteEventResult result = new SPRemoteEventResult(); using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, useAppWeb: false)) { if (clientContext != null) { Web web = clientContext.Web; clientContext.Load(web, w => w.UserCustomActions); clientContext.ExecuteQuery(); if (properties.EventType == SPRemoteEventType.AppInstalled) { clientContext.Load(web, w => w.UserCustomActions, w => w.Url, w => w.AppInstanceId); clientContext.ExecuteQuery(); UserCustomAction userCustomAction = web.UserCustomActions.Add(); userCustomAction.Location = "Microsoft.SharePoint.StandardMenu"; userCustomAction.Group = "SiteActions"; BasePermissions perms = new BasePermissions(); perms.Set(PermissionKind.ManageWeb); userCustomAction.Rights = perms; userCustomAction.Sequence = 100; userCustomAction.Title = "Modify Site"; string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(clientContext.Url)); string issuerId = WebConfigurationManager.AppSettings.Get("ClientId"); var modifyPageUrl = string.Format("https://{0}/Pages/Modify.aspx?{{StandardTokens}}", GetHostUrl()); string url = "javascript:LaunchApp('{0}', 'i:0i.t|ms.sp.ext|{1}@{2}','{3}',{{width:300,height:200,title:'Modify Site'}});"; url = string.Format(url, Guid.NewGuid().ToString(), issuerId, realm, modifyPageUrl); userCustomAction.Url = url; userCustomAction.Update(); clientContext.ExecuteQuery(); // Remove the entry from the 'Recents' node NavigationNodeCollection nodes = web.Navigation.QuickLaunch; clientContext.Load(nodes, n => n.IncludeWithDefaultProperties(c => c.Children)); clientContext.ExecuteQuery(); var recent = nodes.Where(x => x.Title == "Recent").FirstOrDefault(); if (recent != null) { var appLink = recent.Children.Where(x => x.Title == "Site Modifier").FirstOrDefault(); if (appLink != null) { appLink.DeleteObject(); } clientContext.ExecuteQuery(); } } else if (properties.EventType == SPRemoteEventType.AppUninstalling) { foreach (var action in web.UserCustomActions) { if (action.Title == "Modify Site") { action.DeleteObject(); clientContext.ExecuteQuery(); break; } } } } } return(result); }
internal static void UpdateCustomAction(TokenParser parser, PnPMonitoredScope scope, CustomAction customAction, UserCustomAction existingCustomAction, bool isNoScriptSite = false) { var isDirty = false; if (isNoScriptSite) { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_CustomActions_SkippingAddUpdateDueToNoScript, customAction.Name); return; } // Otherwise we update it if (customAction.CommandUIExtension != null) { if (existingCustomAction.CommandUIExtension != parser.ParseString(customAction.CommandUIExtension.ToString())) { scope.LogPropertyUpdate("CommandUIExtension"); existingCustomAction.CommandUIExtension = parser.ParseString(customAction.CommandUIExtension.ToString()); isDirty = true; } } else { // Required to allow for a delta action to blank out the CommandUIExtension attribute if (existingCustomAction.CommandUIExtension != null) { scope.LogPropertyUpdate("CommandUIExtension"); existingCustomAction.CommandUIExtension = null; isDirty = true; } } #if !ONPREMISES if (customAction.ClientSideComponentId != null && customAction.ClientSideComponentId != Guid.Empty) { if (existingCustomAction.ClientSideComponentId != customAction.ClientSideComponentId) { existingCustomAction.ClientSideComponentId = customAction.ClientSideComponentId; } } if (!String.IsNullOrEmpty(customAction.ClientSideComponentProperties)) { if (existingCustomAction.ClientSideComponentProperties != parser.ParseString(customAction.ClientSideComponentProperties)) { existingCustomAction.ClientSideComponentProperties = parser.ParseString(customAction.ClientSideComponentProperties); } } #endif if (existingCustomAction.Description != customAction.Description) { scope.LogPropertyUpdate("Description"); existingCustomAction.Description = customAction.Description; isDirty = true; } #if !ONPREMISES if (customAction.Description.ContainsResourceToken()) { if (existingCustomAction.DescriptionResource.SetUserResourceValue(customAction.Description, parser)) { isDirty = true; } } #endif if (existingCustomAction.Group != customAction.Group) { scope.LogPropertyUpdate("Group"); existingCustomAction.Group = customAction.Group; isDirty = true; } if (existingCustomAction.ImageUrl != parser.ParseString(customAction.ImageUrl)) { scope.LogPropertyUpdate("ImageUrl"); existingCustomAction.ImageUrl = parser.ParseString(customAction.ImageUrl); isDirty = true; } if (existingCustomAction.Location != customAction.Location) { scope.LogPropertyUpdate("Location"); existingCustomAction.Location = customAction.Location; isDirty = true; } if (existingCustomAction.RegistrationId != customAction.RegistrationId) { scope.LogPropertyUpdate("RegistrationId"); existingCustomAction.RegistrationId = customAction.RegistrationId; isDirty = true; } if (existingCustomAction.RegistrationType != customAction.RegistrationType) { scope.LogPropertyUpdate("RegistrationType"); existingCustomAction.RegistrationType = customAction.RegistrationType; isDirty = true; } if (existingCustomAction.ScriptBlock != parser.ParseString(customAction.ScriptBlock)) { scope.LogPropertyUpdate("ScriptBlock"); existingCustomAction.ScriptBlock = parser.ParseString(customAction.ScriptBlock); isDirty = true; } if (existingCustomAction.ScriptSrc != parser.ParseString(customAction.ScriptSrc, "~site", "~sitecollection")) { scope.LogPropertyUpdate("ScriptSrc"); existingCustomAction.ScriptSrc = parser.ParseString(customAction.ScriptSrc, "~site", "~sitecollection"); isDirty = true; } if (existingCustomAction.Sequence != customAction.Sequence) { scope.LogPropertyUpdate("Sequence"); existingCustomAction.Sequence = customAction.Sequence; isDirty = true; } if (existingCustomAction.Title != parser.ParseString(customAction.Title)) { scope.LogPropertyUpdate("Title"); existingCustomAction.Title = parser.ParseString(customAction.Title); isDirty = true; } #if !ONPREMISES if (customAction.Title.ContainsResourceToken()) { if (existingCustomAction.TitleResource.SetUserResourceValue(customAction.Title, parser)) { isDirty = true; } } #endif if (existingCustomAction.Url != parser.ParseString(customAction.Url)) { scope.LogPropertyUpdate("Url"); existingCustomAction.Url = parser.ParseString(customAction.Url); isDirty = true; } if (isDirty) { existingCustomAction.Update(); existingCustomAction.Context.ExecuteQueryRetry(); } }
private static void Startup() { using (var ctx = Context) { Site site = ctx.Site; // Get List var lists = ctx.LoadQuery(site.RootWeb.Lists.Where(l => l.RootFolder.Name == "SiteAssets")); try { ctx.ExecuteQuery(); } catch (Exception ex) { Console.WriteLine($"{ex.Message}\r\n{ex.StackTrace}", ConsoleColor.DarkRed); Console.ReadKey(); Environment.Exit(1); } List siteAssets = lists.FirstOrDefault(); if (siteAssets != null) { // Check if file exists and check out if necessary ctx.Load(site.RootWeb, w => w.ServerRelativeUrl); try { ctx.ExecuteQuery(); } catch (Exception ex) { Console.WriteLine($"{ex.Message}\r\n{ex.StackTrace}", ConsoleColor.DarkRed); Console.ReadKey(); Environment.Exit(1); } var srcShortName = FileShortName.Replace(".js", ".ts"); var jsFile = site.RootWeb.GetFileByServerRelativeUrl($"{site.RootWeb.ServerRelativeUrl.TrimEnd('/')}/SiteAssets/{FileShortName}"); var srcMap = site.RootWeb.GetFileByServerRelativeUrl($"{site.RootWeb.ServerRelativeUrl.TrimEnd('/')}/SiteAssets/{FileShortName}.map"); var src = site.RootWeb.GetFileByServerRelativeUrl($"{site.RootWeb.ServerRelativeUrl.TrimEnd('/')}/SiteAssets/{srcShortName}"); ctx.Load(jsFile, f => f.Exists, f => f.CheckOutType); ctx.Load(srcMap, f => f.Exists, f => f.CheckOutType); ctx.Load(src, f => f.Exists, f => f.CheckOutType); try { ctx.ExecuteQuery(); } catch (ServerException ex) { // expected if the file doesn't exist if (ex.ServerErrorTypeName != "System.IO.FileNotFoundException") { throw; } } // Get File Contents string jsFileContents = System.IO.File.ReadAllText(FilePath); string mapContents = System.IO.File.ReadAllText(FilePath + ".map"); string srcContents = System.IO.File.ReadAllText(SrcPath); // Upload Script File var jsFile2 = siteAssets.RootFolder.Files.Add(new FileCreationInformation { Content = Encoding.UTF8.GetBytes(jsFileContents), Overwrite = true, Url = FileShortName }); var srcMap2 = siteAssets.RootFolder.Files.Add(new FileCreationInformation { Content = Encoding.UTF8.GetBytes(mapContents), Overwrite = true, Url = FileShortName + ".map" }); var src2 = siteAssets.RootFolder.Files.Add(new FileCreationInformation { Content = Encoding.UTF8.GetBytes(srcContents), Overwrite = true, Url = FileShortName.Replace(".js", ".ts") }); Console.WriteLine($"Files have been added!"); Console.WriteLine($"Server synced!"); // Register Custom Action UserCustomAction customAction = site.UserCustomActions.Add(); customAction.Location = "ScriptLink"; customAction.ScriptSrc = $"~SiteCollection/SiteAssets/{FileShortName}"; customAction.Sequence = 1000; customAction.Update(); try { ctx.ExecuteQuery(); } catch (Exception ex) { Console.WriteLine($"{ex.Message}\r\n{ex.StackTrace}", ConsoleColor.DarkRed); Console.ReadKey(); Environment.Exit(1); } } else { throw new FileNotFoundException("'SiteAssets' not found"); } } }
/// <summary> /// </summary> private void AddScriptAdv(ClientContext ctx, Site site, Web web, ref UserActionObjectAdv ucaObj) { UserCustomAction uca = null; if (scope.IsEqual("Site Collection")) { uca = site.UserCustomActions.Add(); } else { uca = web.UserCustomActions.Add(); } if (!ucaObj.commandUIExtension.IsNull()) { uca.CommandUIExtension = ucaObj.commandUIExtension; } if (!ucaObj.descr.IsNull()) { uca.Description = ucaObj.descr; } if (!ucaObj.group.IsNull()) { uca.Group = ucaObj.group; } if (!ucaObj.imageUrl.IsNull()) { uca.ImageUrl = ucaObj.imageUrl; } if (!ucaObj.location.IsNull()) { uca.Location = ucaObj.location; } if (!ucaObj.name.IsNull()) { uca.Name = uca.Title = ucaObj.name; } if (!ucaObj.registrationId.IsNull()) { uca.RegistrationId = ucaObj.registrationId; } if (!ucaObj.scriptBlock.IsNull()) { uca.ScriptBlock = ucaObj.scriptBlock; } if (!ucaObj.scriptSrc.IsNull()) { uca.ScriptSrc = ucaObj.scriptSrc; } uca.Sequence = ucaObj.seq; if (!ucaObj.Url.IsNull()) { uca.Url = ucaObj.Url; } if (ucaObj.registrationType.IsEqual("ContentType")) { uca.RegistrationType = UserCustomActionRegistrationType.ContentType; } else if (ucaObj.registrationType.IsEqual("FileType")) { uca.RegistrationType = UserCustomActionRegistrationType.FileType; } else if (ucaObj.registrationType.IsEqual("List")) { uca.RegistrationType = UserCustomActionRegistrationType.List; } else if (ucaObj.registrationType.IsEqual("None")) { uca.RegistrationType = UserCustomActionRegistrationType.None; } else if (ucaObj.registrationType.IsEqual("ProgId")) { uca.RegistrationType = UserCustomActionRegistrationType.ProgId; } uca.Update(); ctx.Load(uca, x => x.Id, x => x.Name); ctx.ExecuteQuery(); ucaObj.id = uca.Id.ToString(); tcout("Action added", ucaObj.id); }
private void ProvisionCustomActionImplementation(object parent, List <CustomAction> customActions) { Web web = null; Site site = null; if (parent is Site) { site = parent as Site; // Switch parser context; TokenParser.Rebase(site.RootWeb); } else { web = parent as Web; // Switch parser context TokenParser.Rebase(web); } foreach (var customAction in customActions) { var caExists = false; if (site != null) { caExists = site.CustomActionExists(customAction.Name); } else { caExists = web.CustomActionExists(customAction.Name); } if (!caExists) { var customActionEntity = new CustomActionEntity() { CommandUIExtension = customAction.CommandUIExtension != null?customAction.CommandUIExtension.ToString().ToParsedString() : string.Empty, Description = customAction.Description, Group = customAction.Group, ImageUrl = customAction.ImageUrl.ToParsedString(), Location = customAction.Location, Name = customAction.Name, RegistrationId = customAction.RegistrationId, RegistrationType = customAction.RegistrationType, Remove = customAction.Remove, Rights = customAction.Rights, ScriptBlock = customAction.ScriptBlock.ToParsedString(), ScriptSrc = customAction.ScriptSrc.ToParsedString("~site", "~sitecollection"), Sequence = customAction.Sequence, Title = customAction.Title, Url = customAction.Url.ToParsedString() }; if (site != null) { site.AddCustomAction(customActionEntity); } else { web.AddCustomAction(customActionEntity); } } else { UserCustomAction existingCustomAction = null; if (site != null) { existingCustomAction = site.GetCustomActions().FirstOrDefault(c => c.Name == customAction.Name); } else { existingCustomAction = web.GetCustomActions().FirstOrDefault(c => c.Name == customAction.Name); } if (existingCustomAction != null) { var isDirty = false; if (customAction.CommandUIExtension != null) { if (existingCustomAction.CommandUIExtension != customAction.CommandUIExtension.ToString().ToParsedString()) { existingCustomAction.CommandUIExtension = customAction.CommandUIExtension.ToString().ToParsedString(); isDirty = true; } } if (existingCustomAction.Description != customAction.Description) { existingCustomAction.Description = customAction.Description; isDirty = true; } if (existingCustomAction.Group != customAction.Group) { existingCustomAction.Group = customAction.Group; isDirty = true; } if (existingCustomAction.ImageUrl != customAction.ImageUrl.ToParsedString()) { existingCustomAction.ImageUrl = customAction.ImageUrl.ToParsedString(); isDirty = true; } if (existingCustomAction.Location != customAction.Location) { existingCustomAction.Location = customAction.Location; isDirty = true; } if (existingCustomAction.RegistrationId != customAction.RegistrationId) { existingCustomAction.RegistrationId = customAction.RegistrationId; isDirty = true; } if (existingCustomAction.RegistrationType != customAction.RegistrationType) { existingCustomAction.RegistrationType = customAction.RegistrationType; isDirty = true; } if (existingCustomAction.ScriptBlock != customAction.ScriptBlock.ToParsedString()) { existingCustomAction.ScriptBlock = customAction.ScriptBlock.ToParsedString(); isDirty = true; } if (existingCustomAction.ScriptSrc != customAction.ScriptSrc.ToParsedString("~site", "~sitecollection")) { existingCustomAction.ScriptSrc = customAction.ScriptSrc.ToParsedString("~site", "~sitecollection"); isDirty = true; } if (existingCustomAction.Title != customAction.Title.ToParsedString()) { existingCustomAction.Title = customAction.Title.ToParsedString(); isDirty = true; } if (existingCustomAction.Url != customAction.Url.ToParsedString()) { existingCustomAction.Url = customAction.Url.ToParsedString(); isDirty = true; } if (isDirty) { existingCustomAction.Update(); existingCustomAction.Context.ExecuteQueryRetry(); } } } } }
internal static void UpdateCustomAction(TokenParser parser, PnPMonitoredScope scope, CustomAction customAction, UserCustomAction existingCustomAction) { var isDirty = false; // Otherwise we update it if (customAction.CommandUIExtension != null) { if (existingCustomAction.CommandUIExtension != parser.ParseString(customAction.CommandUIExtension.ToString())) { scope.LogPropertyUpdate("CommandUIExtension"); existingCustomAction.CommandUIExtension = parser.ParseString(customAction.CommandUIExtension.ToString()); isDirty = true; } } else { // Required to allow for a delta action to blank out the CommandUIExtension attribute existingCustomAction.CommandUIExtension = null; } if (existingCustomAction.Description != customAction.Description) { scope.LogPropertyUpdate("Description"); existingCustomAction.Description = customAction.Description; isDirty = true; } #if !ONPREMISES if (customAction.Description.ContainsResourceToken()) { if (existingCustomAction.DescriptionResource.SetUserResourceValue(customAction.Description, parser)) { isDirty = true; } } #endif if (existingCustomAction.Group != customAction.Group) { scope.LogPropertyUpdate("Group"); existingCustomAction.Group = customAction.Group; isDirty = true; } if (existingCustomAction.ImageUrl != parser.ParseString(customAction.ImageUrl)) { scope.LogPropertyUpdate("ImageUrl"); existingCustomAction.ImageUrl = parser.ParseString(customAction.ImageUrl); isDirty = true; } if (existingCustomAction.Location != customAction.Location) { scope.LogPropertyUpdate("Location"); existingCustomAction.Location = customAction.Location; isDirty = true; } if (existingCustomAction.RegistrationId != customAction.RegistrationId) { scope.LogPropertyUpdate("RegistrationId"); existingCustomAction.RegistrationId = customAction.RegistrationId; isDirty = true; } if (existingCustomAction.RegistrationType != customAction.RegistrationType) { scope.LogPropertyUpdate("RegistrationType"); existingCustomAction.RegistrationType = customAction.RegistrationType; isDirty = true; } if (existingCustomAction.ScriptBlock != parser.ParseString(customAction.ScriptBlock)) { scope.LogPropertyUpdate("ScriptBlock"); existingCustomAction.ScriptBlock = parser.ParseString(customAction.ScriptBlock); isDirty = true; } if (existingCustomAction.ScriptSrc != parser.ParseString(customAction.ScriptSrc, "~site", "~sitecollection")) { scope.LogPropertyUpdate("ScriptSrc"); existingCustomAction.ScriptSrc = parser.ParseString(customAction.ScriptSrc, "~site", "~sitecollection"); isDirty = true; } if (existingCustomAction.Sequence != customAction.Sequence) { scope.LogPropertyUpdate("Sequence"); existingCustomAction.Sequence = customAction.Sequence; isDirty = true; } if (existingCustomAction.Title != parser.ParseString(customAction.Title)) { scope.LogPropertyUpdate("Title"); existingCustomAction.Title = parser.ParseString(customAction.Title); isDirty = true; } #if !ONPREMISES if (customAction.Title.ContainsResourceToken()) { if (existingCustomAction.TitleResource.SetUserResourceValue(customAction.Title, parser)) { isDirty = true; } } #endif if (existingCustomAction.Url != parser.ParseString(customAction.Url)) { scope.LogPropertyUpdate("Url"); existingCustomAction.Url = parser.ParseString(customAction.Url); isDirty = true; } if (isDirty) { existingCustomAction.Update(); existingCustomAction.Context.ExecuteQueryRetry(); } }
internal static void UpdateCustomAction(TokenParser parser, PnPMonitoredScope scope, CustomAction customAction, UserCustomAction existingCustomAction) { var isDirty = false; // Otherwise we update it if (customAction.CommandUIExtension != null) { if (existingCustomAction.CommandUIExtension != parser.ParseString(customAction.CommandUIExtension.ToString())) { scope.LogPropertyUpdate("CommandUIExtension"); existingCustomAction.CommandUIExtension = parser.ParseString(customAction.CommandUIExtension.ToString()); isDirty = true; } } else { // Required to allow for a delta action to blank out the CommandUIExtension attribute if (existingCustomAction.CommandUIExtension != null) { scope.LogPropertyUpdate("CommandUIExtension"); existingCustomAction.CommandUIExtension = null; isDirty = true; } } if (existingCustomAction.Description != customAction.Description) { scope.LogPropertyUpdate("Description"); existingCustomAction.Description = customAction.Description; isDirty = true; } #if !ONPREMISES if (customAction.Description.ContainsResourceToken()) { if (existingCustomAction.DescriptionResource.SetUserResourceValue(customAction.Description, parser)) { isDirty = true; } } #endif if (existingCustomAction.Group != customAction.Group) { scope.LogPropertyUpdate("Group"); existingCustomAction.Group = customAction.Group; isDirty = true; } if (existingCustomAction.ImageUrl != parser.ParseString(customAction.ImageUrl)) { scope.LogPropertyUpdate("ImageUrl"); existingCustomAction.ImageUrl = parser.ParseString(customAction.ImageUrl); isDirty = true; } if (existingCustomAction.Location != customAction.Location) { scope.LogPropertyUpdate("Location"); existingCustomAction.Location = customAction.Location; isDirty = true; } if (existingCustomAction.RegistrationId != customAction.RegistrationId) { scope.LogPropertyUpdate("RegistrationId"); existingCustomAction.RegistrationId = customAction.RegistrationId; isDirty = true; } if (existingCustomAction.RegistrationType != customAction.RegistrationType) { scope.LogPropertyUpdate("RegistrationType"); existingCustomAction.RegistrationType = customAction.RegistrationType; isDirty = true; } if (existingCustomAction.ScriptBlock != parser.ParseString(customAction.ScriptBlock)) { scope.LogPropertyUpdate("ScriptBlock"); existingCustomAction.ScriptBlock = parser.ParseString(customAction.ScriptBlock); isDirty = true; } if (existingCustomAction.ScriptSrc != parser.ParseString(customAction.ScriptSrc, "~site", "~sitecollection")) { scope.LogPropertyUpdate("ScriptSrc"); existingCustomAction.ScriptSrc = parser.ParseString(customAction.ScriptSrc, "~site", "~sitecollection"); isDirty = true; } if (existingCustomAction.Sequence != customAction.Sequence) { scope.LogPropertyUpdate("Sequence"); existingCustomAction.Sequence = customAction.Sequence; isDirty = true; } if (existingCustomAction.Title != parser.ParseString(customAction.Title)) { scope.LogPropertyUpdate("Title"); existingCustomAction.Title = parser.ParseString(customAction.Title); isDirty = true; } #if !ONPREMISES if (customAction.Title.ContainsResourceToken()) { if (existingCustomAction.TitleResource.SetUserResourceValue(customAction.Title, parser)) { isDirty = true; } } #endif if (existingCustomAction.Url != parser.ParseString(customAction.Url)) { scope.LogPropertyUpdate("Url"); existingCustomAction.Url = parser.ParseString(customAction.Url); isDirty = true; } if (isDirty) { existingCustomAction.Update(); existingCustomAction.Context.ExecuteQueryRetry(); } }
protected void btnSave_Click(object sender, EventArgs e) { siteURL = Page.Request["SPHostUrl"]; var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { clientContext.Load(clientContext.Site); clientContext.ExecuteQuery(); if (clientContext.Site.ShareByEmailEnabled) { initialSharingSetting = _shared; } else { initialSharingSetting = _notshared; } } try { if (rdbList.SelectedValue == "allowed" && initialSharingSetting == _notshared) { Log.LogFileSystem(string.Format("Start enabling external sharing...")); Log.LogFileSystem(string.Format("\t" + "Start getting Context...")); var ctx = GetContext(TenantAdminUrl); using (ctx) { Tenant _tenant = new Tenant(ctx); Log.LogFileSystem(string.Format("\t" + "Loading site properties...")); SiteProperties _siteProps = _tenant.GetSitePropertiesByUrl(siteURL, false); ctx.Load(_tenant); ctx.Load(_siteProps); ctx.ExecuteQuery(); bool _shouldBeUpdated = false; var _tenantSharingCapability = _tenant.SharingCapability; var _siteSharingCapability = _siteProps.SharingCapability; var _targetSharingCapability = SharingCapabilities.Disabled; //if (siteInfo.EnableExternalSharing && _tenantSharingCapability != SharingCapabilities.Disabled) //{ _targetSharingCapability = SharingCapabilities.ExternalUserSharingOnly; _shouldBeUpdated = true; //} if (_siteSharingCapability != _targetSharingCapability && _shouldBeUpdated) { Log.LogFileSystem(string.Format("\t" + "Enabling sharing setting...")); _siteProps.SharingCapability = _targetSharingCapability; ctx.Load(_siteProps); SpoOperation op = _siteProps.Update(); ctx.Load(op, i => i.IsComplete); ctx.ExecuteQuery(); while (!op.IsComplete) { Log.LogFileSystem(string.Format("\t" + "Refreshing update...")); //wait 30seconds and try again System.Threading.Thread.Sleep(3000); op.RefreshLoad(); ctx.ExecuteQuery(); } Log.LogFileSystem(string.Format("\t" + "Update completed!")); } } try { Log.LogFileSystem(string.Format("\t" + "Start enabling the banner...")); //Enable Banner var clientContextSC = GetContext(siteURL); using (clientContextSC) { Site site = clientContextSC.Site; clientContextSC.Load(site); clientContextSC.ExecuteQuery(); var existingActions = site.UserCustomActions; clientContextSC.Load(existingActions); clientContextSC.ExecuteQuery(); UserCustomAction targetAction = existingActions.Add(); targetAction.Name = "External_Sharing_Banner"; targetAction.Description = "External_Sharing_Banner"; targetAction.Location = "ScriptLink"; targetAction.ScriptBlock = "var headID = document.getElementsByTagName('head')[0]; var externalSharingTag = document.createElement('script'); externalSharingTag.type = 'text/javascript'; externalSharingTag.src = '" + JavaScriptFile + "';headID.appendChild(externalSharingTag);"; targetAction.ScriptSrc = ""; targetAction.Update(); clientContextSC.ExecuteQuery(); Log.LogFileSystem(string.Format("\t" + "Banner successfully enabled!")); EventLog.WriteEntry(source, string.Format("Changing External Sharing Settings is completed successfully. The Site Collection is externally shared and the banner is enabled."), EventLogEntryType.Information, 6000); } } catch (Exception ex) { EventLog.WriteEntry(source, string.Format("Error occurred in changing External Sharing Settings. The error is {0}", ex.Message), EventLogEntryType.Error, 6001); } } else if (rdbList.SelectedValue == "notallowed" && initialSharingSetting == _shared) { Log.LogFileSystem(string.Format("Start disabling external sharing...")); Log.LogFileSystem(string.Format("\t" + "Start getting Context...")); var ctx = GetContext(TenantAdminUrl); using (ctx) { Tenant _tenant = new Tenant(ctx); Log.LogFileSystem(string.Format("\t" + "Loading site properties...")); SiteProperties _siteProps = _tenant.GetSitePropertiesByUrl(siteURL, false); ctx.Load(_tenant); ctx.Load(_siteProps); ctx.ExecuteQuery(); bool _shouldBeUpdated = false; var _tenantSharingCapability = _tenant.SharingCapability; var _siteSharingCapability = _siteProps.SharingCapability; var _targetSharingCapability = SharingCapabilities.Disabled; _targetSharingCapability = SharingCapabilities.Disabled; _shouldBeUpdated = true; if (_siteSharingCapability != _targetSharingCapability && _shouldBeUpdated) { Log.LogFileSystem(string.Format("\t" + "Disabling sharing setting...")); _siteProps.SharingCapability = _targetSharingCapability; ctx.Load(_siteProps); SpoOperation op = _siteProps.Update(); ctx.Load(op, i => i.IsComplete); ctx.ExecuteQuery(); while (!op.IsComplete) { Log.LogFileSystem(string.Format("\t" + "Refreshing update...")); //wait 30seconds and try again System.Threading.Thread.Sleep(3000); op.RefreshLoad(); ctx.ExecuteQuery(); } } } try { Log.LogFileSystem(string.Format("\t" + "Start disabling the banner...")); //Disable Banner var clientContextSC = GetContext(siteURL); using (clientContextSC) { Site site = clientContextSC.Site; clientContextSC.Load(site); clientContextSC.ExecuteQuery(); var existingActions = site.UserCustomActions; clientContextSC.Load(existingActions); clientContextSC.ExecuteQuery(); var actions = existingActions.ToArray(); foreach (var action in actions) { if (action.Name == "External_Sharing_Banner" && action.Location == "ScriptLink") { action.DeleteObject(); clientContextSC.ExecuteQuery(); Log.LogFileSystem(string.Format("\t" + "Banner successfully disabled!")); break; } } } EventLog.WriteEntry(source, string.Format("Changing External Sharing Settings is completed successfully. The Site Collection is not externally shared and the banner is disabled."), EventLogEntryType.Information, 6000); } catch (Exception ex) { EventLog.WriteEntry(source, string.Format("Error occurred in changing External Sharing Settings. The error is {0}", ex.Message), EventLogEntryType.Error, 6001); } } Log.LogFileSystem(string.Format(string.Format("External Sharing is now {0} ", rdbList.SelectedValue))); Log.LogFileSystem(string.Format("External Sharing setting is changed successfully for Site Collection - {0} ", Page.Request["SPHostUrl"])); Log.LogFileSystem(string.Empty); //Response.Redirect((string.IsNullOrEmpty(siteURL) ? Page.Request["SPHostUrl"] : siteURL) + "/_layouts/15/settings.aspx"); ScriptManager.RegisterStartupScript(this, this.GetType(), "successMessageBanner", "alert('External Sharing setting is changed successfully!!'); window.location='" + (string.IsNullOrEmpty(siteURL) ? Page.Request["SPHostUrl"] : siteURL) + "/_layouts/15/settings.aspx';", true); } catch (System.Threading.ThreadAbortException ex) { Response.Redirect((string.IsNullOrEmpty(siteURL) ? Page.Request["SPHostUrl"] : siteURL) + "/_layouts/15/settings.aspx", false); } catch (Exception ex) { Log.LogFileSystem(string.Format("Error occured in changing External Sharing Settings for Site Collection - {0}, error is {1} ", (string.IsNullOrEmpty(siteURL) ? Page.Request["SPHostUrl"] : siteURL), ex.Message)); Log.LogFileSystem(string.Empty); EventLog.WriteEntry(source, string.Format("Error occured in changing External Sharing Settings. The error is {0}", ex.Message), EventLogEntryType.Error, 6001); ScriptManager.RegisterStartupScript(this, GetType(), "ErrorMessageBanner", "document.getElementById('spanErrorMsg').style.display = 'block';", true); ScriptManager.RegisterStartupScript(this, GetType(), "ErrorCursor", " document.body.style.cursor = 'default';", true); } }