Ctrl Alt X

04 December 2013

SharePoint-Hosted Apps, Rest Call and trust

This is  a quick one, when working with SharePoint-Hosted Apps, you dont always need to trust the app. This works if you are writing JSOM code like this:

'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function() {
// This code runs when the DOM is ready and creates a context object which is
    // needed to use the SharePoint object model
$(document).ready(function () {
// This function prepares, loads, and then executes a SharePoint query to get
    // the current users information
function getUserName() {
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
// This function is executed if the above call is successful
    // It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
'#message').html('<h1>Hello ' + user.get_title() + "</h1>");
function getTitle() {
'#message').append("</br><div><span>Host Web: </span><strong>" + getParameterByName("SPHostUrl") + "</strong></div>")
"</br><div><span>App Web: </span><strong>" + getParameterByName("SPAppWebUrl") + "</strong></div>")
"</br><div><span>Complete Url: </span><strong>" + window.location.href + "</strong></div>")
function getParameterByName(name) {
        name = name.replace(
/[\[]/, "\\\[").replace(/[\]]/, "\\\]")
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
'Failed to get user name. Error:' + args.get_message());

But if you using Rest API to access some resource you might get:

403 value=Access denied. You do not have permission to perform this action or access this resource.

Here is the code that I am try to run

'use strict';
var hostWebUrl;
var appWebUrl;

function () {
function appendToMessage(text) {
return $("#message").append("<p>" + text + "</p>")
function () {
hostWebUrl = getParameterByName(
appWebUrl = getParameterByName(
var remoteExecScript = hostWebUrl + "/_layouts/15/SP.RequestExecutor.js"
$.getScript(remoteExecScript, getSPHostWeb)
function getSPHostWeb() {
"<h3>Making Ajax Call to host web...</h3>")
"<h3>Trying another site collection...</h3>")
function executeRestCall(targetWebUrl) {
var uri = appWebUrl + "/_api/SP.AppContextSite(@target)/web?@target='" + targetWebUrl + "'"
var executor = new SP.RequestExecutor(appWebUrl)
url: uri,
headers: {
"Accept": "application/json;odata=verbose" },
success: onGetSPHostWebSuccess,
error: onGetSPHostWebFail
function onGetSPHostWebSuccess(restRawJSON) {
'<strong>Success to rest call ... title of web is "' + getSPRestResultObject(restRawJSON).Title + '"</strong>');
function getTitle() {
"<span>Host Web: </span><strong>" + hostWebUrl + "</strong>")
"<span>App Web: </span><strong>" + appWebUrl + "</strong>")
"<span>Complete Url: </span><strong>" + window.location.href + "</strong>")
function getParameterByName(name) {
name = name.replace(
/[\[]/, "\\\[").replace(/[\]]/, "\\\]")
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
function onGetSPHostWebFail(data) {
'<div style="color:red">Failed to get Host Web: ' + JSON.parse(data.body).error.message.value + '</div>');
function getSPRestResultObject(data) {
return JSON.parse(data.body).d

To fix the error don’t forget to Trust the App!! that’s it:

Which raises another question: How do you make call to rest point in another site collection. As I am doing it in this line:

appWebUrl + "/_api/SP.AppContextSite(@target)/web?@target='https://mycompany.com/sites/someothersitecollection"

This is possible with SP.AppContextSite, this can be used in JSOM and Rest calls. You can set it to any site collection to make the calls. Now there are couple of things that you need to make sure. According to MS deployment scope for the app should be tenet scope http://msdn.microsoft.com/en-us/library/office/fp179896.aspx

Here is another detailed discussion http://blogs.msdn.com/b/officeapps/archive/2012/11/29/solving-cross-domain-problems-in-apps-for-sharepoint.aspx 

03 December 2013

Setting Office 365 SharePoint Site Collection for App Development

Note: Information on this post applies to E3 and E4 o365 hosting plan.

There are two ways to develop using a Office 365 site when developing Apps:

1) Use site created with development site template. You can do this from SharePoint Online Admin center or follow this link http://msdn.microsoft.com/en-us/library/office/jj692554.aspx .

2) If you decide to develop/debug using non-development site template, you will need to follow few steps. I will assume you have a team site and we will install few things in order to get our team site to allow us to develop Apps.

I will make simple SharePoint-hosted App with no server side code. This is probably the simplest type of app that can be made to test our setup. I am using Visual Studio 2013, this works with Visual Studio 2010. When you create a simple SharePoint-Hosted app and hit the “run” button, if the site that you provided when creating the project is not based on development site template you will get:

Sideloading of apps is not enabled on this site

In order to develop with this team site you will need to activate “development site” feature on this site. Now this feature is not available from site collection feature or site feature. You will need to use powershell to activate this feature. I am using a window 7 machine. To setup my machine for powershell, first I downloaded PowerShell 3.0 from http://www.microsoft.com/en-us/download/details.aspx?id=34595

Once my powershell was downloaded, open powershell terminal with “Run  as Administrator” and set the execution policy to RemoteSigned by running:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned​

Next you need to download "SharePoint Online Management Shell" from http://www.microsoft.com/en-us/download/details.aspx?id=35588

Once you have installed the SharePoint Online management shell, we will use it to connect it to o365 tenet using CSOM. Run the following Snippet

Import-Module Microsoft.Online.SharePoint.Powershell
$developerFeature = "e374875e-06b6-11e0-b0fa-57f5dfd72085"
$siteUrl =
$userName = “you@yourcompany.com
$password = ConvertTo-SecureString -String "yourpassword" -AsPlainText -Force
[Microsoft.SharePoint.Client.ClientContext]$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($siteurl)  
$clientContext.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $password)
$site = $clientContext.Site;   
$featureguid = new-object System.Guid $developerFeature    
$site.Features.Add($featureguid, $true, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None);

Now try again to deploy you app using “run” in visual studio. This time every thing should be fine!!

Thanks to:


08 May 2013

Changing Usage and Health Data Collection Database

I cruppeted my usage and health database!! In my database I see it as Suspect state.

This is my development machine, so obviously I don't have any database backup. I went through couple of post  to fix the suspended database, but then...it seems lot of work.

I took a different route to use new database for Usage and Health data. Here are the steps;
1) Create a new database using following command:

 USE master;  
 ALTER DATABASE SP2013_Auto_Config
 COLLATE Latin1_General_CI_AS_KS_WS;  

Critical thing to make sure is database collation is set to "Latin1_General_CI_AS_KS_WS":

 SELECT name, collation_name  
 FROM sys.databases  
 WHERE name = N'SP2013_Auto_Config';  

SharePoint will not allow you change the Usage database unless it's collation is collect.
Once you have done that use following powershell to change the database:

  set-spusageapplication -Identity "Usage and Health Data Collection Service Application" -DatabaseName "sp2013_Auto_SA_Usage2" -DatabaseServer "SP2013\sharepoint"