Add ApplicationInsights to your O365 SharePoint sites

If you use ApplicationInsights in your SharePoint Apps you might also want to include it in all sites of the hosting web. You can do this by injecting the corresponding JavaScript using the client side object model (CSOM) and UserCustomActions.

Go to https://portal.azure.com/ and open your ApplicationInsights-Application or create a new one. Go to “Quick start” – “Get code to monitor my web pages” and copy the code insight the script tags.

image

Save the script to a JavaScript file and upload it to your O365 site (i.e. to /Style%20Library).

image

Use the following PowerShell script to inject the JavaScript file without modifying the master page or deploying any kind of solution.

$username = "user@xxx.onmicrosoft.com" 
$password = "<your password>" 
$url      = "https://xxx.sharepoint.com/sites/xxx"
$jsurl    = "$url/Style%20Library/AppInsights.js"


$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force 

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")

$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url) 
$clientContext.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword) 


if (!$clientContext.ServerObjectIsNull.Value) 
{ 
    Write-Host "Connected to SharePoint Online site: '$Url'" -ForegroundColor Green 
} 

$id       = "AppInsights"
$revision    = [guid]::NewGuid().ToString().Replace("-", "")
$jsLink      = "$($jsurl)?rev=$revision"
$scriptBlock = "var headID = document.getElementsByTagName('head')[0]; 
                var newScript = document.createElement('script');
                newScript.type = 'text/javascript';
                newScript.src = '$jsLink';
                headID.appendChild(newScript);"

$web = $clientContext.Web

$existingActions = $web.UserCustomActions
$clientContext.Load($existingActions)
$clientContext.ExecuteQuery()

foreach ($action in $existingActions)
{
    if ($action.Description -eq $id -and $action.Location -eq "ScriptLink")
    {
        $action.DeleteObject()
        $clientContext.ExecuteQuery()
    }
}

$newAction = $existingActions.Add()
$newAction.Description = $id
$newAction.Location = "ScriptLink"
$newAction.ScriptBlock = $scriptBlock
$newAction.Update()
$clientContext.Load($web)
$clientContext.ExecuteQuery()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s