blog.scoreman.net

Archive for the ‘SharePoint Online’ Category

Week numbers in calendar view – revisited for SharePoint Online

Tuesday, September 9th, 2014

A long time ago I wrote some posts on how you could add week numbers to the monthly calendar view both in SharePoint 2007 and in SharePoint 2010. The solution in SP2007 depended on overriding the calendar’s control template using server side code. Since full trust code is no option in SharePoint Online that does not work. The solution in SP2010 used client side JavaScript but since the calendar view is totally rewritten in SP2013 the SP2010 solution does not work either. So I thought that I would revisit this topic once again for a Office 365/SharePoint Online/SharePoint 2013 version.

The code basically has two main parts. First we need to intercept the client side calls that the calendar view does in SharePoint 2013. Thanks to this post for showing how to do that.

Contoso.WeekNumber.InterceptCalendarEvent = function () {
    ExecuteOrDelayUntilScriptLoaded(function () {
        var onItemsSucceed = SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed;
        SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed = function ($p0, $p1) {
            onItemsSucceed.call(this, $p0, $p1);
            Contoso.WeekNumber.AddWeekNumbers();
        };
    }, "SP.UI.ApplicationPages.Calendar.js");
}

Secondly using JQuery we can find all TH elements and add week numbers.

Contoso.WeekNumber.AddWeekNumbers = function () {
    $(".ms-acal-month > TBODY > TR > TH[evtid='week']").each(function () {
        var firstDay = new Date($(this).attr("date"));
        if (firstDay.toString() != "NaN" && firstDay.toString() != "Invalid Date") {
            var week = firstDay.getWeek(firstDay.getDay());
            week = (week.toString().length == 1) ? '0' + week.toString() : week.toString();
            $(this).html("<div class='ms-picker-weekbox'><acronym title='Week number " + week + "'>" + week + "</acronym></div>");
            $(this).attr("class", "ms-picker-week");
            $(this).css("vertical-align", "middle");
        }
    });
}

For calculating week numbers I used the same JavaScript function that I used in the post on how to add week numbers in SharePoint 2010. It calculates week numbers based on the Gregorian calendar but you can replace that function with whatever you want.

I’ve attached a working solution that is ready to deploy to Office 365. Run the solution from Visual Studio, trust the app and then click on the init button. If all goes well JQuery and a custom javascript file will be added to the site assets library. Also custom actions will be added to the host web so that the scripts are included during page load. This example also works with minimum download strategy (MDS) turned on. The end result looks like this:

week numbers

Get term store in SharePoint Online

Thursday, February 13th, 2014

This is just ta small tips when working with taxonomy client-side object model and SharePoint Online. You will find lots of examples like the one below online:

var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
var termStores = taxSession.get_termStores();
var termStore = termStores.getByName("Taxonomy_Dmxzz8tIBzk8wNVKQpJ+xA==");

The important thing to note is that the name of the term store (something like Taxonomy_Dmxzz8tIBzk8wNVKQpJ+xA==) can and will change over time. This can happen if the service (Office 365) creates a new Managed Metadata Service Application or even fails over to another data center. To prevent the code from crashing a better approach could be to use getDefaultSiteCollectionTermStore:

var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
var termStores = taxSession.get_termStores();
var termStore = taxSession.getDefaultSiteCollectionTermStore();

Preserving ClientId and ClientSecret in Windows Azure

Friday, January 10th, 2014

Here is a quick tips if you are building SharePoint Provider Hosted Apps in Windows Azure. If there are several developers publishing an app (or if you are using publishing in Visual Studio Online) to Windows Azure chances are that ClientId and ClientSecret will be changed in the web.config file. When ClientId and ClientSecret are changed the app will no longer be able to communicate with SharePoint unless you register the app again with the new ClientId and ClientSecret.

Another way to solve this would be to prevent the ClientId and ClientSecret to change. This can be done by overriding what is in the web.config file using built in functionality in Azure. If you set appsettings in the Azure Portal or using solution explorer in Visual Studio these settings will override what is in the web.config file. This way your ClientId and ClientSecret will match what was in the app manifest when the app was registered in SharePoint.

Setting appSettings through the Windows Azure Portal

Setting appSettings through the Windows Azure Portal

Setting appSettings through solution explorer in Visual Studio

Setting appSettings through solution explorer in Visual Studio

Create Site Collections in SharePoint Online using CSOM

Tuesday, February 26th, 2013

This week I’m working with a customer that wants their users to be able to create site collections in SharePoint Online. Below is a step-by-step guide how this can be done using the Client Side Object Model in SharePoint 2013.

UPDATE 2014-01-15: Registering a

Prerequisites

The example application is created on my Windows 8 desktop computer without SharePoint 2013 installed. The following applications are required:

  • Visual Studio 2012
  • Microsoft Office Developer Tools for Visual Studio 2012
  • SharePoint Online Management Shell

Create a Client Application

In this example I’ve created a simple console application but it might as well be a service running in Azure or any other .NET application. Start by creating a Windows console application and add assembly references to:

  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.Runtime.dll
  • Microsoft.Online.SharePoint.Client.Tenant.dll

The assemblies can be found here: C:Program FilesSharePoint Online Management ShellMicrosoft.Online.SharePoint.PowerShell.

Add TokenHelper Class

To make it easier for developers Microsoft has created a helper class used for OAuth communication with SharePoint. This example aslo uses this class and it can be included by creating a new App for SharePoint (provider or autohosted) in Visual Studio project and then copying the TokenHelper.cs file into the console application. Change the namespace in the class to match the console applications namespace. The class requires references to the following assemblies:

  • System.Web.dll
  • System.ServiceModel.dll
  • System.IdentityModel.dll
  • System.Web.Extensions.dll
  • Microsoft.IdentityModel.dll
  • Microsoft.IdentityModel.Extensions.dll

Add the Code

Start by adding these two using statements to Program.cs:

using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;

Then simply add the following code inside the Main-method:


            var SHAREPOINT_PID = "00000003-0000-0ff1-ce00-000000000000"; // SharePoint constant
            var tenantAdminUri = new Uri("https://<TENANT>-admin.sharepoint.com");
            var token = TokenHelper.GetAppOnlyAccessToken(SHAREPOINT_PID, tenantAdminUri.Authority, null).AccessToken;

            using (var context = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token))
            {
                var tenant = new Tenant(context);
                var properties = new SiteCreationProperties()
                {
                    Url = "https://<TENANT>.sharepoint.com/sites/site1",
                    Owner = "<USER>@<TENANT>.onmicrosoft.com",
                    Template = "STS#0",
                    StorageMaximumLevel = 1000,
                    UserCodeMaximumLevel = 300
                };
                tenant.CreateSite(properties);

                context.Load(tenant);
                context.ExecuteQuery();
            }

All occurences of <TENANT> should be replaced with your real tenant name and also <USER> should be replaced with the username of whoever is going to be the owner of the site collection.

Register the Application in SharePoint Online

For this to work the application must be registered in your Office 365 tenant and also given tenant permissions. To do this first navigate to https://<TENANT>.sharepoint.com/_layouts/appregnew.aspx. Click on the buttons to generate an App Id and an App Secret. Fill in a Title, App Domain and Redirect URI and click on the Create button. You will be taken to a summery page. Copy the App Id and App Secret values because you will be needing them later.

Next you need to give the application tenancy permission. This can be done by going to https://<TENTANT>.sharepoint.com/_layouts/appinv.aspx. Fill in your App Id and hit Lookup. Now paste the following XML in Permission Request XML and click Create:

<AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
</AppPermissionRequests>

You will be taken to a summary page saying that this application requires full control of all site collections, access basic user information and share its permission with other users. Click Trust it.

Finally you need to find out the app realm. Navigate to https://<TENANT>.sharepoint.com/_layouts/appprincipals.aspx. Identify the row with your registered application and look at the App Identifier column. The unique identifier after the @-sign in the App Identifier is the app realm. Copy the realm (not the whole App Identifier just the last part after the @-sign).

Finish the Client Application

The App Id, App Secret and App Realm now needs to be added to the client application. If your console application does not have an app.config add one and then add these appSettings inside the configuration element:

  <appSettings>
    <add key="ClientId" value="<APP ID>"/>
    <add key="ClientSecret" value="<APP SECRET>"/>
    <add key="Realm" value="<APP REALM>"/>
  </appSettings>

Replace , <APP ID>, <APP SECRET> and < APP REALM> with the values you got from SharePoint Online. The application should now be ready for testing. Not many lines of code but some wiring up to make it work with OAuth and SharePoint Online.