Update permission of SharePoint List Item using CSOM: Fix for Cannot add a role assignment with empty role definition binding collection
There should not be any executequeries between below statements.So do get the principal at before below lines.
RoleDefinitionBindingCollection collRoleDefinitionBindingAssignee = new RoleDefinitionBindingCollection(clientContext);
RoleDefinition targetRoleDefinition = clientContext.Web.RoleDefinitions.GetByName(“Definition Name”);
clientContext.Load(targetRoleDefinition);
collRoleDefinitionBindingAssignee.Add(targetRoleDefinition);
oListItem.RoleAssignments.Add(principle, collRoleDefinitionBindingAssignee);
//Only one ExecuteQuery should be at the end.
clientContext.ExecuteQuery();
SharePoint Designer Cache Folders
Below are the cache folders of SharePoint Designer 2013 and those need to be cleared when cache related issues occured.
%APPDATA%\Microsoft\Web Server Extensions\Cache
%APPDATA%\Microsoft\SharePoint Designer\ProxyAssemblyCache
%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache
Setting ‘Show field’ for “Person or Group” type column using PowerShell
Taken from https://prasadpathak.wordpress.com/2013/10/10/setting-show-field-for-person-or-group-type-column-using-powershell/
When using Person or Group field and you need to change how the field value is displayed change the show field value.
Bellow image shows the “show field” option on Edit column page.
<Field Type="User" DisplayName="My User Column" List="UserInfo" Required="FALSE" ShowField="ImnName" UserSelectionMode="1" UserSelectionScope="0" Group="Custom Columns" ID="{}" SourceID="{}" StaticName="MyUserColumn" Name="MyUserColumn" > </Field>
| Sr.No. | Show Field drop down options | Exact value need to pass LookupField property |
| 1 | Name | Title |
| 2 | Account | Name |
| 3 | Work email | |
| 4 | Mobile phone | MobilePhone |
| 5 | SIP Address | SipAddress |
| 6 | Department | Department |
| 7 | Title | JobTitle |
| 8 | First name | FirstName |
| 9 | Last name | LastName |
| 10 | Work phone | WorkPhone |
| 11 | User name | UserName |
| 12 | Office | Office |
| 13 | ID | ID |
| 14 | Modified | Modified |
| 15 | Created | Created |
| 16 | Name (with presence) | ImnName |
| 17 | Picture Only (36×36) | PictureOnly_Size_36px |
| 18 | Picture Only (48×48) | PictureOnly_Size_48px |
| 19 | Picture Only (72×72) | PictureOnly_Size_72px |
| 20 | Name (with picture and details) | NameWithPictureAndDetails |
| 21 | Content Type | ContentTypeDisp |
Taken from https://prasadpathak.wordpress.com/2013/10/10/setting-show-field-for-person-or-group-type-column-using-powershell/
Dynamically Load JavaScript Files and Execute Function
Source: http://unixpapa.com/js/dyna.html
The trick is to give the same name to the script loading function and the function that needed to be executed. Then when first clicked it will load the JS file and excute function because of the function execute line in loaded JS. After that the JS loading function will get overridden by the loaded function.
<input type="button" onclick="helper()" value="Helper">
function helper()
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'helper.js';
head.appendChild(script);
}
The script file being loaded looks something like this:
function helper()
{
:
lots of code
:
}
:
more function and global variable definitions
:
helper();
Automating add-in/app installation to SharePoint sites using CSOM
“How do I install apps/add-ins from store, app catalog or directly to the site?” is relatively common question cross partners and customers. We are getting this question or request quite often at the Office 365 Developer Patterns and Practices (PnP) Yammer group or through other forums. Frank Marasco from the Office Dev PnP core team blogged about this already while back with title of “SideLoading Guideance” (Finglish is contagious), but due the amount of questions, thought that it would be worth while to have another blog post on the same topic.
Before heading to the actual meat of the post, let’s have a short look on the different options of the getting your add-in/app deployed, so that we understand the different options and requirements around the request.
Add-in/app scoping
There is two different ways for add-in/app to exist in the SharePoint or to be visible in the sites and it’s important to understand the difference so that we can decide the right deployment mechanism for add-in/apps.
Web scoped add-ins/apps
This is more typical model where add-in/app is located directly in the context of specific site. Add-in/app is installed directly to the site and is visible in the site contents view. Web scoped add-ins/apps can install app parts, app custom actions and app installed events are firing for provider hosted add-in when they are added to the site. Following drawing explains the model in practice.
- End users are adding add-ins/apps to SharePoint sites
- App is created or instantiated directly to the site and it can have optional app/add-in web, which is created directly under the specific site. Add-in/app webs are basically just sub sites in the site collections with specific template. App-in/app installed events are fired in the case of the provider hosted add-ins/apps and optional app parts, including optional custom actions, are being visible in the host web where the add-in/app was installed
- User accesses the add-in from the site contents or from add-in/app part
- Content is rendered from the add-in/app. Could come from provider hosted environment or from the add-in/app web
Tenant scoped add-ins/apps
This is capability also know as “app stapling” where you install add-in to app catalog site collection and then use “Deployment” mechanism to push the add-in/app available for other sites. Add-in/app is only installed once to the app catalog site collection and in other sites there will be just links pointing to this centralized instance under app catalog. This means that custom actions and app parts are being deployed only to app catalog and not to the other sites where the app is being visible. Also app install, uninstall and upgrade events are only executed on the app catalog site context, since that’s the actual location where the app is being installed.
Richard diZerega has great blog post on this few years back called SharePoint 2013 app deployment through “app stapling”.
- Add-ins/apps are being installed by app catalog owner
- Add-in/app is being installed on the app catalog. Possible app events, app parts, custom actions are being visible in the app catalog site after the initial creation of the app. This is the only location where the app actually is being installed
- Users access the add-in/app from their browsers at the normal sites
- Add-ins/apps have been pushed to the normal sites with the “Deployment” mechanism, which makes them visible in the site contents view, but does not really install the add-in/app to the sites
How to automate web scoped add-in/app installation?
Coming back on the actual topic of the post. Since you cannot use tenant scoped deployment model to get add-in parts or custom actions to be visible in the sites, it’s relatively common ask to get web scoped add-ins/apps deployed to sites for example as part of the initial site provisioning. This is actually possible, but has few limitations, due security challenges and store processes. We cannot achieve this for add-ins/apps in the store, but we can actually make this work within enterprise development scenarios, where you have control of the add-ins/apps which are being installed.
Pre-requisites
There are few different pre-requisites for making add-ins/apps being installed directly to the sites using web scoped approach. Here’s a short list of the pre-requisites.
- Add-in/app which being installed has to request tenant level permissions, which is the reason why this is not suitable model for store add-ins/apps
- Add-in/app which being installed has to be instantiated or specifically trusted by the tenant administrator once before it can be pushed to sites
- Add-in/app which being installed has to be pushed by uploading app file directly to the site where it’s being added
- You cannot push add-ins/apps from the store or from the app catalog to the sites
- When you install add-in/app to the site, you will need to enable so called site loading feature
- Regardless of the statement in the blog post at Office Apps MSDN blog, this is fully supported. It’s not specifically recommended due the fact that then you do not have centralized control on the add-in/app, but it’s also the only way to achieve certain business scenarios.
How does it work in practice?
Let’s have a look on the process and code in practice with the following video. This shows quickly the app-stapling process and also what are the steps getting add-ins/apps installed on any SharePoint using CSOM, with app part and custom action support. To be able to install add-in/apps directly to the site using CSOM, you’ll need to perform following steps
- Install add-in/app once on the tenant level to grant the needed permissions for the add-in/app
- Connect to SharePoint site
- Enabled side loading feature at site collection level
- Install add-in/app using Web.LoadAndInstallApp method
- Deactivate side loading feature at site collection level
You can also find this video from the Office 365 Developer Patterns and Practices video blog at Channel 9.
CSOM code to install and app/add-in to SharePoint site
Here’s the full code of the console application, which is used to connect to SharePoint online and install add-in/app to the site.
// Unique ID for side loading feature
Guid sideloadingFeature = new Guid("AE3A1339-61F5-4f8f-81A7-ABD2DA956A7D");
// Prompt for URL
string url = GetUserInput("Please provide URL for the site where app is being installed: \n");
// Prompt for Credentials
Console.WriteLine("Enter Credentials for {0}", url);
string userName = GetUserInput("SharePoint username: ");
SecureString pwd = GetPassword();
// Get path to the location of the app file in file system
string path = GetUserInput("Please provide full path to your app package: \n");
// Create context for SharePoint online
ClientContext ctx = new ClientContext(url);
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ctx.Credentials = new SharePointOnlineCredentials(userName, pwd);
// Get variables for the operations
Site site = ctx.Site;
Web web = ctx.Web;
try
{
// Make sure we have side loading enabled.
// Using PnP Nuget package extensions.
site.ActivateFeature(sideloadingFeature);
try
{
// Load .app file and install that to site
var appstream = System.IO.File.OpenRead(path);
AppInstance app = web.LoadAndInstallApp(appstream);
ctx.Load(app);
ctx.ExecuteQuery();
}
catch
{
throw;
}
// Disable side loading feature using
// PnP Nuget package extensions.
site.DeactivateFeature(sideloadingFeature);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(string.Format("Exception!"), ex.ToString());
Console.WriteLine("Press any key to continue.");
Console.Read();
}
Q&A
Can I automate app/add-in installation for apps in the SharePoint store?
No. This is not possible, since store apps have licensing implications, so they cannot be just installed using simple API calls.
Can I automate app/add-in installation from app-catalog
Slightly depends on the exact objective. You can push add-ins/apps from the catalog using “app-stapling” model, but that has limitation around app parts, custom actions and app installation events. With app-stapling you create instance of the add-in/app to the app catalog site collection and then push links to specific sites. You cannot deploy isolated instances of the add-in/app to different sites and site collections. You can only achieve this with the code and process explained in this blog post.
Can I use app-one/add-in only token to install app on the site using this code?
No. This does not work, since app-only means that you are basically running in the system context and SharePoint cannot associate app/add-in to the right person in the app service application. Code will execute, but installation will fail in the UI in the end like with following picture.
Video shows deployment of provider hosted add-in/app to SharePoint sites, but would same process work with SP hosted add-in?
No. Model where you actually create own app instances to specific sites with LoadAndInstallApp() does only work for provider hosted add-ins/apps. App stapling from app catalog works for SP hosted add-ins and provider hosted add-ins.
Add-in/app has to request tenant level permissions, so it can only then be used by tenant administrator?
No. Trust operation has to be done by tenant administrator, but actual API calls in the add-in/app do not require that high permissions. Add-in/app could for example perform read or write operations to host web, which would only require that level of permission from the end user using the app/add-in. Alternatively add-in/app which has been installed, could use app-only permissions which basically means same as classic elevation of privileges in server side code.
Is there any other way to make this work?
Yes. You could always fall back on so called http post pattern, but that’s not also recommended approach since that means that you’d mimic browser operations for the “Trust” operation by mimicking the needed http post traffic. This does work, but if there’s any changes in the UI of the targeted operation, your code could get broken. We do not intentially do UI changes which would break these, but we cannot also guarantee that changes which would impact your code would not be done.
Office 365 Developer Patterns and Practices
Techniques showed in this blog post are part of the Core.SideLoading sample in the Office 365 Developer Patterns and Practices guidance, which contains more than 100 samples and solutions demonstrating different patterns and practices related on the app model development together with additional documentation related on the app model techniques.
Check the details around PnP from dev.office.com at https://aka.ms/OfficeDevPnP. Please join us on sharing patterns and practices for the community for the benefit of the community. If you have any questions, comments or feedback related on this sample, blog post or anything on PnP, please use the Office 365 Developer Patterns and Practices Yammer group at https://aka.ms/OfficeDevPnPYammer.
“Sharing is caring”
Ribbon Action Locations(Custom Actions)
https://msdn.microsoft.com/en-us/library/office/bb802730.aspx
The following table shows the locations, custom action group IDs, and custom action IDs that are used in the CustomAction element and theCustomActionGroup element of custom actions that are installed by default in Microsoft SharePoint Foundation.
In the table, each location value corresponds to the Location attribute of the CustomAction element. Each group ID corresponds to theGroupId attribute of the CustomAction element or to the Id attribute of the CustomActionGroup element. Each custom action ID corresponds to the Id attribute of the CustomAction element.
You can create a Feature that implements the HideCustomAction element to hide any default custom action that is identified in the table.
| Location | Custom Action Group IDs | Default Custom Action IDs | Group Description | |
|---|---|---|---|---|
| DisplayFormToolbar | Not applicable |
|
Location corresponds to the display form toolbar of lists. | |
| EditControlBlock | Not applicable | Not applicable | Location corresponds to the per-item edit control block (ECB) menu. | |
| EditFormToolbar | Not applicable | Not applicable | Location corresponds to the edit form toolbar of lists. | |
| NewFormToolbar | Not applicable | Not applicable | Location corresponds to the new form toolbar of lists. | |
| ViewToolbar | Not applicable | Not applicable | Location corresponds to the toolbar in list views. | |
| Microsoft.SharePoint.StandardMenu | ActionsMenu | Not applicable | Actions menu in list and document library views. | |
| Microsoft.SharePoint.StandardMenu | ActionsMenuForSurvey | Not applicable | Site Actions menu for surveys. | |
| Microsoft.SharePoint.StandardMenu | SettingsMenuForSurvey | Not applicable | Site Settings links for surveys. | |
| Microsoft.SharePoint.StandardMenu | SiteActions | Not applicable | Site Actions menu. | |
| Location | Custom Action Group IDs | Default Custom Action IDs | Group Description | |
|---|---|---|---|---|
| Microsoft.SharePoint.ContentTypeSettings | Fields |
|
Columns section on site collectionContent Typepage. | |
| Microsoft.SharePoint.ContentTypeSettings | General |
|
Settings section on site collectionContent Typepage. | |
| Microsoft.SharePoint.ContentTypeTemplateSettings | Fields |
|
Columns section on List Content Type page. | |
| Microsoft.SharePoint.ContentTypeTemplateSettings | General |
|
Settings section on List Content Type page. | |
| Microsoft.SharePoint.Create | WebPages | Not applicable | Web Pagessection on Createpage. | |
| Microsoft.SharePoint.GroupsPage | NewMenu | Not applicable | New menu on site collectionPeople and Groups page. | |
| Microsoft.SharePoint.GroupsPage | SettingsMenu | Not applicable | Settings menu on site collectionPeople and Groups page. | |
| Microsoft.SharePoint.ListEdit | Communications | Not applicable | Communicationssection onCustomize page for list or document library. | |
| Microsoft.SharePoint.ListEdit | GeneralSettings | Not applicable | General Settingssection onCustomize page for list. | |
| Microsoft.SharePoint.ListEdit | Permissions | Not applicable | Permissions and Managementsection onCustomize page for list or document library. | |
| Microsoft.SharePoint.ListEdit.DocumentLibrary | GeneralSettings | Not applicable | General Settingssection onCustomize page for document library. | |
| Microsoft.SharePoint.PeoplePage | ActionsMenu | Not applicable | Actions menu on site collectionPeople and Groups page. | |
| Microsoft.SharePoint.PeoplePage | NewMenu | Not applicable | New menu on site collectionPeople and Groups page. | |
| Microsoft.SharePoint.PeoplePage | SettingsMenu | Not applicable | Settings menu on site collectionPeople and Groups page. | |
| Microsoft.SharePoint.SiteSettings | Customization |
|
Look and Feelsection on Site Settings page. | |
| Microsoft.SharePoint.SiteSettings | Galleries |
|
Galleries section on Site Settingspage. | |
| Microsoft.SharePoint.SiteSettings | SiteAdministration |
|
Site Administrationsection on Site Settings page. | |
| Microsoft.SharePoint.SiteSettings | SiteCollectionAdmin |
|
Site Collection Administrationsection on Site Settings page. | |
| Microsoft.SharePoint.SiteSettings | UsersAndPermissions |
|
Users and Permissionssection on Site Settings page. | |
| Location | Custom Action Group ID | Description | |
|---|---|---|---|
| Microsoft.SharePoint.Administration.Applications | Databases | Databases section under Application Management in Central Administration | |
| ServiceApplications | Service Applicationssection underApplication Management in Central Administration | ||
| SiteCollections | Site Collectionssection underApplication Management in Central Administration | ||
| WebApplications | Web Applicationssection underApplication Management in Central Administration | ||
| Microsoft.SharePoint.Administration.Backups | FarmBackup | Farm Backup and Restore section underBackup and Restorein Central Administration | |
| GranularBackup | Granular Backupsection under Backup and Restore in Central Administration | ||
| Microsoft.SharePoint.Administration.ConfigurationWizards | FarmConfiguration | Farm Configurationsection underConfiguration Wizards in Central Administration | |
| Microsoft.SharePoint.Administration.Default |
|
Default page in Central Administration | |
| Microsoft.SharePoint.Administration.GeneralApplicationSettings | ExternalServiceConnections | External Service Connections section under General Application Settingsin Central Administration. | |
| SiteDirectory | Site Directory section under General Application Settingsin Central Administration. | ||
| SPD | SharePoint Designersection under General Application Settingsin Central Administration. | ||
| Microsoft.SharePoint.Administration.Monitoring | HealthStatus | Health Analyzersection underMonitoring in Central Administration | |
| Reporting | Reporting section under Monitoring in Central Administration | ||
| TimerJobs | Timer Jobs section under Monitoring in Central Administration | ||
| Microsoft.SharePoint.Administration.Security | GeneralSecurity | General SecuritySection under Securityin Central Administration. | |
| InformationPolicy | Information PolicySection under Securityin Central Administration. | ||
| Users | Users Section underSecurity in Central Administration. | ||
| Microsoft.SharePoint.Administration.SystemSettings | E-Mail and Text Messages (SMS)section under System Settings in Central Administration. | ||
| Farm Management | Farm Managementsection under System Settings in Central Administration. | ||
| Servers | Servers section underSystem Settings in Central Administration. | ||
| Microsoft.SharePoint.Administration.UpgradeAndMigration | Patch | Upgrade and Patch Management section under Upgrade and Migration in Central Administration. | |
| Location | Custom Action Group IDs | Default Custom Action IDs | Group Description | |
|---|---|---|---|---|
| CommandUI.Ribbon.ListView | Not applicable | See Default Server Ribbon Customization Locations | Location corresponds to the list view. | |
| CommandUI.Ribbon.NewForm | Not applicable | See Default Server Ribbon Customization Locations | Location corresponds to the new form for the list. | |
| CommandUI.Ribbon.EditForm | Not applicable | See Default Server Ribbon Customization Locations | Location corresponds to the edit form for the list. | |
| CommandUI.Ribbon.DisplayForm | Not applicable | See Default Server Ribbon Customization Locations | Location corresponds to the display form for the list. | |
| CommandUI.Ribbon | Not applicable | See Default Server Ribbon Customization Locations | Location corresponds to the list view and edit, new, and display forms for the list. | |
MSDN Article for CommandUIHandler Element
https://msdn.microsoft.com/en-us/library/office/ff458385.aspx
Applies to: SharePoint Foundation 2013 | SharePoint Server 2013
In this article
Attributes
Child Elements
Parent Elements
Occurrences
Defines the handler for a command.
<CommandUIHandler Command = "Text" CommandAction = "Text" EnabledScript = "Text" />
| Attribute | Description | ||
|---|---|---|---|
| Command | Required. The name of a command. The value of this attribute matches the value of a Command attribute on an element that defines a control. | ||
| CommandAction | Required. A script statement to execute when this handler is invoked. Microsoft SharePoint Foundation calls theeval method, passing in the value of this attribute.
The value of the attribute can contain substitution tokens that are transformed at rendering. The following tokens are recognized:
|
||
| EnabledScript | Optional.
A script statement that is executed to determine whether the command is enabled or disabled. The script expression should return a Boolean value, true if the command is enabled and false if not. If the ribbon is disabled, commands are grayed out and are not clickable. As with the CommandAction attribute, the eval method is called with the value of this attribute as an argument. The EnabledScript attribute does not support the substitution tokens that are described for the CommandActionattribute. |
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction
Id="EmailContacts"
RegistrationType="List"
RegistrationId="105"
Location="CommandUI.Ribbon">
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location="Ribbon.ListItem.Actions.Controls._children">
<Button
Id="Ribbon.ListItem.Actions.Email"
Alt="$Resources:core,E-Mail;"
Sequence="55"
Command="emailContacts"
LabelText="$Resources:core,E-Mail;"
Description="$Resources:core,E-Mail;"
TemplateAlias="o1"/>
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="emailContacts"
CommandAction="javascript:
function getItemIds()
{
var itemIds = '';
var items = SP.ListOperation.Selection.getSelectedItems();
var item;
for(var i in items)
{
item = items[i];
if(itemIds != '')
{
itemIds = itemIds + ',';
}
itemIds = itemIds + item.id;
}
return itemIds;
}
function handleReadyStateChange()
{
if (client.readyState == 4)
{
if (client.status == 200)
{
// client.responseText is mailto string
window.location = ('mailto:' + client.responseText);
}
}
}
function invokeEmailContacts()
{
var params = 'itemids=' + getItemIds();
// Posting to EmailContacts.ashx to get the mailto string
var site='{SiteUrl}';
var url = site + '/_layouts/emailcontacts.ashx?listId={ListId}';
client = null;
client = new XMLHttpRequest();
client.onreadystatechange = handleReadyStateChange;
client.open('POST', url, true);
client.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
client.setRequestHeader('Content-length', params.length);
client.send(params);
}
invokeEmailContacts();"
EnabledScript="javascript:
function enableEmailContacts()
{
var items = SP.ListOperation.Selection.getSelectedItems();
return (items.length > 0);
}
enableEmailContacts();"/>
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
</Elements>
Get Value of SharePoint People Picker in Visual Studio Workflow
If you create a Person/Group field in a list say with the name Field1, you get the value of the field using Field1Id.
Source: http://mazdev.blogspot.ae/2014/05/get-value-of-persongroup-list-item.html
Service accounts for SharePoint
Below are set of service account that can be used when setting up the SharePoint environment.
Service Accounts
SP_Farm
SP_Admin
SP_Services
SP_Pool
SP_Search
SP_Crawl
SP_UserProfiles
SQL Service Accounts
SQL_Admin
SQL_Services
Send Test Mail Using Telnet
Open power-shell windows and enter below command.
PS C:\Users\admin> Send-MailMessage -SMTPServer localhost -To xxxxx@gmail.com -From blog@vsysad.com -Subject "This is a test email" -Body "This is a test email sent via PowerShell"

Note