Access Denied on O365

Recently while working on a utility, I faced a very unusual error. I was trying to remove default documents from document set using managed client object model (Default Documents) and it was giving me classic “Access denied. You do not have permission to perform this action or access this resource” error, even though my account had site collection admin as well as tenant admin rights. Besides that, I was doing other operations on the same document set and it was working perfectly fine. One thing to notice was, this error was present only in root site collection and not in another site collections.

After searching a lot, I realized that this is happening due to a certain setting at tenant level and that was “Custom Script”. So if you navigate to SharePoint admin center and click on Settings, there is a section for custom script which says “Prevent users from running custom script on self-service created sites”. This is enabled by default and you need to “Allow users to run custom script on self-service created sites” for this to work. Also note that this change may take up to 24 hours to take effect.

CustomScript

I am not sure about the reason behind this behavior but hope this helps someone.

Besides access denied issue, other issues which I faced if custom script is turned off for root site collection are:

  1. I was not able to open root site collection in SP Designer and it was giving me “Forbidden” error. The complete error was “you do not have permission to open this web site in sharepoint designer
  2. Content Editor and Script Editor web parts were not available in the root site collection.

    Once this feature was turned on, both of the issues were solved.

Happy coding!

CSOM – Check If My Site Exists

There are times when we want to know whether My Site exist for a particular user. In general, My Site is created when a user accesses the My Site (i.e. the “About Me” link) for the first time. For more details on My Site architecture check this msdn link.

Using CSOM, we can fetch a particular user’s my site link. The code for that is:

The above code returns my site url of the user but if my site does not exist then also it returns the my site host url of that user. So, in this case the url returned is something like:

https://tenant-my.sharepoint.com/Person.aspx?accountname=accountnameofuser

This does not tell us whether my site actually exist or not unless we do some url manipulation. But there is a peroperty in the same code which returns my site relative url only if it exists and that property is PersonalSpace. This is present in UserProfileProperties of PeopleManager class.

The code to fetch that is :

This will return blank if my site does not exist else will return /personal/email_of_user

P.S. The code above could also be used in apps, just give Read permission to User Profile.

Happy Coding!!