403 Forbidden when deleting SPWeb (JSOM) REST call Office365

When attempting to DELETE a SharePoint sub web within some included JavaScript (as opposed to a SharePoint App), you can simply call a REST endpoint, and pass the ‘DELETE’ verb as a HTTP header.

This is using the $.ajax method of jQuery.

You just need to use the URL of the subweb you want to delete – with the “_api/web” suffix.

var urlToDelete = 'http://tenant.sharepoint.com/sites/corp/web/subweb1/_api/web';

And – to then do a call to the REST endpoint, you just construct JavaScript like this :

$.ajax({
        url: urlToDelete,
        method: 'POST',
        headers: {
            'Accept': 'application/json; odata=verbose', 
            'X-HTTP-Method': 'DELETE'
        },
        success: function (data) {
            alert('success');
        },
        error: function (err) {
            alert('fail');
        }
    }); 

BUT – and this is what caught me out – you might get a “403 Forbidden” error.    If you check using F12 developer tools – you’ll see the error.

The trick is to include the content of the page (hidden variable) – and use as another header :

$('#__REQUESTDIGEST').val()

And so – when you add it all together – you get this – and it works !    and no 403 error…

$.ajax({
        url: urlToDelete,
        method: 'POST',
        headers: {
            'Accept': 'application/json; odata=verbose', 
            'X-HTTP-Method': 'DELETE',
            'X-RequestDigest': $('#__REQUESTDIGEST').val()
        },
        success: function (data) {
            alert('success');
        },
        error: function (err) {
            alert('fail');
        }
    });

If you get a 500 error – it maybe that there are “subwebs” – and you need to delete those first.

Get SharePoint Apps for current web using JavaScript CSOM (Office 365)

We have a requirement for a right hand pane set-of-links, which is essentially a set of shortcuts to the “APPS” that are within the SITE CONTENTS page.   This will be shown on the home page of a SharePoint SPWeb, in a short list, rather than the user viewing all the big tiles, etc.

The basic steps are :

  • Get the current SPContext for the web
  • Get the AppTiles for the current web
  • Cycle through, and get the TITLE and TARGET (URL) for each tile
  • Inject the HTML in using jQuery

I simply saved this as a file called “allApps.htm” and then added a Content Editor WebPart.   There are only a few lines of HTML – just a placeholder :

image

And then, there’s a stack of JavaScript – yay !

image

Here’s what it looks like when displayed in the CEWP, inside a Page – needs some CSS magic – but it works !

image

And – if you want to use the above technique – here’s the code :

var ctxCurrent;
var ctxWeb;

//get the SharePoint context
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', loadContext);

function loadContext() {
    ctxCurrent = new SP.ClientContext.get_current();
    ctxWeb = ctxCurrent.get_web();
    loadAppTiles();
}

function loadAppTiles() {
    //get the appTiles
    var appTiles = ctxWeb.get_appTiles();
    ctxCurrent.load(appTiles);

    //go through them all - and find the app for 'class workspace provisioning';
    ctxCurrent.executeQueryAsync(
        function onQuerySucceeded(sender, args) {
            if (appTiles.get_count() > 0) {
                //go through the appTiles - get the TITLE and TARGET - and jQuery them into the UL
                for (var i = 0; i < appTiles.get_count() ; i++) {
                    //get the tile at the "i" number
                    appTile = appTiles.getItemAtIndex(i);

                    //grab the title and url
                    appTitle = appTile.get_title();
                    appUrl = appTile.get_target();

                    //append to the UL - using jQuery
                    var newLi = "<li><a href='" + appUrl + "' >" + appTitle + "</a></li>";
                    $jq('#currentApps ul').append(newLi);
                }
            }
        },
        function onQueryFailed(sender, args) {
            console.error('getAppTile. Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }
    );
}

Let me know if this was helpful – cheers !

🙂

Office365 Master Page change via jQuery injection

With the SharePoint platform in Office365, there’s one school-of-thought to NOT change the Master Page.   This will allow for any changes downstream, from Microsoft – if/when new features are to be included.

We used to include a whole stack of changes to Master Pages within the SP2010 and SP2013 environment, but need to approach this in a different way – OR – miss out on the new changes/updates.

Anyway, we’re going with that approach – NO changes to Master Page.

And so, the requirement I have is to include a ‘footer’ on each page – which would traditionally be included in a Master Page.   

How do I do it ??

The approach I’m now taking is to use some ‘JavaScript+HTML’ injection – provisioned using remote PowerShell – and CSOM.

The main steps are :

  • Connect to SharePoint online – using credentials – and establish a ‘context’
  • Upload the files needed – jQuery and custom code JS (and CSS if needed)
  • Include a CustomAction that registers a ScriptBlock – in the Master Page (startup.js)
  • Within the startup.js, reference my other code libraries (JS files)

Connect to SharePoint Online

$urlAdmin = https://YOUR.TENANT-admin.sharepoint.com
$user = “administrator@YOUR.TENANT.onmicrosoft.com”
$password = “YOUR.TENANT.PASSWORD”
$urlSite =
https://YOUR.TENANT.sharepoint.com/sites/TestSiteCollection 

$passwordSecureString = ConvertTo-SecureString -string $password -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $user, $passwordSecureString

Connect-SPOService -Url $urlAdmin -Credential $credential

$spoCredentials = New-Object -TypeName Microsoft.SharePoint.Client.SharePointOnlineCredentials -argumentlist $user, $passwordSecureString

$spoCtx = New-Object Microsoft.SharePoint.Client.ClientContext($urlSite)
$spoCtx.Credentials = $spoCredentials
$spoCtx.RequestTimeout = “500000”

Upload the files

Ignoring the CSS for now, I have TWO files to upload to my SharePoint site – these will just land in the SiteAssets library – or you could use StyleLibrary – either is OK.

  • jquery-2.1.3.min.js     (could use a CDN URL I guess)
  • CLIENTNAME.O365.startup

(Not including the PowerShell to upload files – that’s a topic for another blog post)

Include a CustomAction

This next bit of PowerShell will register a <SCRIPTBLOCK> within the page, and thereby, inject my specific JavaScript/jQuery/etc.

$newAction = $spoCtx.Site.UserCustomActions.Add();
$newAction.Location = “ScriptLink”;
$newAction.scriptSrc = “~SiteCollection/SiteAssets/scripts/jquery-2.1.3.min.js“;
$newAction.Sequence = 1001;
$newAction.Update();
$spoCtx.ExecuteQuery();

$newAction = $spoCtx.Site.UserCustomActions.Add();
$newAction.Location = “ScriptLink”;
$newAction.scriptSrc = “~SiteCollection/SiteAssets/scripts/CLIENTNAME.O365.startup.js“;
$newAction.Sequence = 1002;
$newAction.Update();
$spoCtx.ExecuteQuery();

Here you can see that my JS’s are now referenced – and thus it’s worked (the above steps).

image

Reference other JS files

Within my ‘startup.js’, I can now call out to other JavaScript files – one in particular is to update a FOOTER on the site collection.   

I’ve ALSO chosen to centralize these files – so that I can change it ONCE and all site collections are updated – nice !

Switching over to JavaScript now, this is the code within the “startup.js” :

var $jq = jQuery.noConflict();

// load the SHARED scripts from central location
$jq.getScript(‘/siteassets/BRANDING/scripts/jquery-ui-1.11.4.min.js’);

$jq.getScript(‘/siteassets/BRANDING/scripts/CLIENTNAME.O365.footer.js’);

Update the footer – via JS

I can now do whatever I like with the HTML markup – and style accordingly via CSS.    I’m only showing part of the footer code here – it’s up to YOU what you need.

$jq(document).ready(function () {

    //load the footer contents
    var footerHtml = “<div id=’ClientFooter’ class=’ms-dialogHidden’>”;
    footerHtml = footerHtml + “<div class=’footerSection1′>”;

    footerHtml = footerHtml + “<div class=’text’>”;
    footerHtml = footerHtml + “<a href=’
http://www.homepage.com.au’><img alt=’Logo’ src=’/SiteAssets/BRANDING/Images/logo.png’ /></a>”;
    footerHtml = footerHtml + “</div>”;

    footerHtml = footerHtml + “<ul>”;
    footerHtml = footerHtml + “<li><a href=’
https://www.homepage.com.au/’>AAAAAA</a></li>”;
    footerHtml = footerHtml + “<li><a href=’www.homepage.com.au/pages/BBBBBB.aspx’>BBBBBB</a></li>”;
    footerHtml = footerHtml + “</ul>”;

    footerHtml = footerHtml + “<div class=’footerSection2′>”;
        footerHtml = footerHtml + “<div class=’text’>”;
            footerHtml = footerHtml + “<h3>Contact Us</h3>”;
            footerHtml = footerHtml + “<p>If you would like to email us :</p>”;
            footerHtml = footerHtml + “<ul>”;
            footerHtml = footerHtml + “<li><a id=’contact’ onclick=’loadEmailForm();’ href=’#’>Click here to send email</a></li>”;
            footerHtml = footerHtml + “</ul>”;
        footerHtml = footerHtml + “</div>”;
    footerHtml = footerHtml + “</div>”;

   $jq(‘#s4-workspace’).append(footerHtml);

});

It’s essentially just “build a string” – and then use jQuery to inject at the bottom of the page (#s4-workspace).

After doing a bunch of CSS and HTML – it can look really nice !

Conclusion

So – there you have it – a fairly simple approach to make ‘page changes’ without messing with the Master Page.

Unless Microsoft ditch the “s4-workspace” DIV, my code is fairly safe – and it works….

Let me know your thoughts on this approach – it’s been a interesting one to develop.

🙂

Content Organizer Rule (CSOM/O365)

Our client is using Office365, and we’re provisioning new sites using an Azure WebJob, which will do the necessary configuration.

One aspect they want is to do the “Content Organizer” rule.   This will mean people can upload to a document library (DropOff Lib), and it will be re-routed.  

This is for school students to submit assignment work.

After looking at CSOM code, and searching on Google for stuff like “EcmDocumentRouterRule”, I had a brain wave to just do it SIMPLE – for my fairly simple rule.

The Content Organizer from SiteSettings is just a SharePoint list – and ListItems are added.  So – looking at the REST API – there are simply a bunch of properties ;

https://TENANT.sharepoint.com/sites/SearchTest1/_api/web/lists/RoutingRules/Items(1)

image

So – it follows that I simply need to create a listitem – and it just works !

image

** NB.  PRIOR TO THIS, need to make sure you have turned ON the feature :

// Load the features
FeatureCollection webFeatures = clientCtx.Web.Features;
clientCtx.Load(webFeatures);
clientCtx.ExecuteQuery();

//turn on site feature for Content Organizer, will create drop off library
webFeatures.Add(new Guid(“7ad5272a-2694-4349-953e-ea5ef290e97c”), false, FeatureDefinitionScope.None);
clientCtx.Load(webFeatures);
clientCtx.ExecuteQuery();

Here’s the code, ready to copy+paste :

//only way to do within CSOM is to add the necessary listitem to “ROUTINGRULES” list  
List routingRulesList = clientCtx.Web.Lists.GetByTitle(“Content Organizer Rules”);
clientCtx.Load(routingRulesList);
clientCtx.ExecuteQuery();

//get the current url, to use when defining target for rule
var web = clientCtx.Web;
clientCtx.Load(web);
clientCtx.ExecuteQuery();

var currentUrl = web.Url;
string targetLibraryUrl = currentUrl + “/SubmittedWork”;

ListItemCreationInformation routingRuleInfo = new ListItemCreationInformation();
ListItem routingRule = routingRulesList.AddItem(routingRuleInfo);
routingRule[“Title”] = “Move to Submitted library”;
routingRule[“RoutingRuleName”] = “Move to Submitted library”;
routingRule[“RoutingPriority”] = 1;
routingRule[“RoutingEnabled”] = true;
routingRule[“RoutingContentType”] = “Document”;
routingRule[“RoutingConditionProperties”] = “Content Type”;
routingRule[“RoutingTargetLibrary”] = “Submitted Work”;
routingRule[“RoutingTargetPath”] = targetLibraryUrl;
routingRule[“RoutingRuleExternal”] = false;
routingRule[“RoutingAliases”] = null;
routingRule[“RoutingRuleDescription”] = null;
routingRule[“RoutingTargetFolder”] = null;
routingRule[“RoutingAutoFolderProp”] = null;
routingRule[“RoutingCustomRouter”] = null;

routingRule.Update();
clientCtx.ExecuteQuery();
 

Hopefully that helps with your Office365 configuration – good luck !

🙂

SharePoint page showing BLANK

I have an Office 365 site collection that I’ve been provisioning from within PowerShell – and automatically uploading webparts.   I’m getting some weird behaviour though :

image

When looking at VIEW SOURCE – it’s even stranger – that’s the ENTIRE page !

image

Even when looking at the page request/s via FIDDLER – nothing seemed off.   And nothing in the console or error log in the F12 developer tools.

I could view the page with the ?contents=1 appended to the URL – but still no answer.

image

I worked out that it’s actually a SEARCH webpart that is causing the issue – but I couldn’t work out WHY…

This was my PowerShell code to upload the webpart to the page – some other O365 guff around this – but this is the basic code (using CSOM) :

$wpm = $pubFile.GetLimitedWebPartManager([Microsoft.SharePoint.Client.WebParts.PersonalizationScope]::Shared);       
$wpcoll = $wpm.WebParts
$spoCtx.Load($wpcoll)
$spoCtx.ExecuteQuery();

$webPartFileContents = [System.IO.File]::ReadAllText($filepath);
$wpd = $wpm.ImportWebPart($webPartFileContents);

$wpdNew = $wpm.AddWebPart($wpd.WebPart, $xmlwp.ZoneID, $webPartCount);
$spoCtx.Load($wpdNew);
$spoCtx.ExecuteQuery();

Within the .WEBPART file, there’s the usual XML bits & pieces – and a bunch of properties.

Resolution

After lots of blog post hunting – off/on for a few days actually – and re-building the WebPart contents piece-by-piece, I noticed it was breaking on properties like this >

<property name=”RenderTemplateId” type=”string”>~sitecollection/_catalogs/masterpage/Display Templates/Search/Control_SearchResults.js</property>

It was THIS post from Chris O’Brien that made me hunt down this path :

http://www.sharepointnutsandbolts.com/2013/04/provisioning-content-search-web-part.html

..but then the page does not load (blank screen, HTML not output properly) and ULS shows the following runtime error:

Application error when access /SitePages/CSWP_Provisioned.aspx, Error=Cannot make a cache safe URL for “item_picture3lines_cob_provisioned.js”, file not found. Please verify that the file exists under the layouts directory.
at Microsoft.SharePoint.Utilities.SPUtility.MakeBrowserCacheSafeLayoutsUrl(String name, Boolean localizable, Int32 desiredVersion)   

I couldn’t check the log files – with Office 365 – but I think it’s the same issue.

My next thing to try was to change the markup within my .WEBPART – and I had success !

image

Changed to :

image

Just needed to change from ~ to the equivalent in encoding ~

I’m unsure exactly WHY this is occurring – perhaps the PowerShell upload is losing this and/or encoding it wrong – but it worked !

Hopefully that helps someone – or at least, this post is a reference for ME, if it ever happens AGAIN !

Office 365 send email using JavaScript (REST)

I have a fairly simple requirement for some JavaScript (jQuery) to send an email.   This is within the code for a SharePoint Online page (Office 365).

My initial thinking was to do a HTTP POST request to the Office 365 REST endpoint, but nothing could have prepared me for the next few hours of my day.

I had to jump through a few hoops, and perform backflips while juggling – and THEN changed tack entirely.   I thought I’d share my observations – and some sample code/link.

This was my starting point (MSDN) :    Send a new message on the fly (REST)

I wrangled with it for a few hours :

  • SharePoint hosted code (JS), calling to https://outlook.office365.com was resulting in a 401 – due to a X-Domain call.
  • HTTP POST with JSONP doesn’t work – only for GET
  • CORS is what was messing it up – 401’ing the request
  • Even trialling with the new http://graph.microsoft.com – same problem
  • Suggestions via Twitter were to do an Azure AD app – TO SEND AN EMAIL !!
  • I even found one ridiculous solution that was to create workflow from Visual Studio or SharePoint Designer – and then CALL it from CSOM.    #WTF !!

A colleague mentioned “surely SharePoint has something to send an email” – it could then process the email traffic SERVER SIDE.   

That was an unholy yee-haar gold nugget of joy.

Posting from my jQuery back to SharePoint Online is a simple REST call.   And, it does NOT suffer from X-Domain or CORS.    

http://tenant/_api/SP.Utilities.Utility.SendEmail

There’s a blog post that I found, with a great code sample – and it’s now working for me :

Sending email with SharePoint and jQuery

Just note that the recipient is limited to a valid SharePoint user for security reasons.    (within the same tenant)

So – it’s the simply “KISS” principle – keep it simple, stupid.   

😉

Add to Office365 PropertyBag (PowerShell)

Been fiddling with some script to ADD a value to the PropertyBag for a SharePoint site within Office365.

There’s a great post (and script) on the Microsoft site – for READING all properties :

How to read all property bags in a SharePoint Online Site Collection

But, for adding a new key, I had to fiddle & find an answer.

This post also – mentions the issue with “persisting” values :

Add and Retrieve property bag by CSOM (thanks !!)

NB.   This code (PowerShell) will only ADD a key/value – if not already in place.    (You’ll need to change slightly – to UPDATE the value)

        $rootWeb = $spoCtx.Web
        $spoCtx.Load($rootWeb);
        $spoCtx.ExecuteQuery();

        $allProps = $rootWeb.AllProperties;
        $spoCtx.Load($allProps);
        $spoCtx.ExecuteQuery();

        # DOESN’T WORK !!
        # $allProps.FieldValues.Add(‘KEY’, $value);

        $rootWeb.AllProperties[‘KEY’] = $value;
        $rootWeb.Update();


        $spoCtx.ExecuteQuery();

That’s not TOO tricky in the end – just needed some fiddley syntax to make it work – especially the POWERSHELL bit…

Hope that helps you – it was a battle for me.   

🙂

Yammer from C# – create a group

There’s a surprisingly woeful lack of doco and information about using the API for Yammer – from C# especially – there’s more for the JavaScript way, but not for .NET.

The one I need – to create a Yammer Group – is this one :

https://www.yammer.com/api/v1/groups.json?name={0}&private={1}

The best approach is to simply call the REST API – using the .NET Web Client classes (HttpWebRequest).

It follows that you need to do a POST to this URL – the clincher is to define an ‘accessToken’ to do so.   This is like a SharePoint 2013 style ClientId/ClientSecret.

Click here to register your app, and get the token – it is then registered against YOUR Yammer network.   

image

You’ll get a CLIENTID and CLIENTSECRET – need to plug these into the following URL >

https://www.yammer.com/oauth2/authorize?client_id=[:client_id]&redirect_uri=[:redirect_uri]

And then you’ll get a CODE value.    THEN, need to call the following >

https://www.yammer.com/oauth2/access_token.json?client_id=[:client_id]&client_secret=[:client_secret]&code=[:code]

And you’ll get a TOKEN – which is the magic bean you need for the following C# code.

Here’s some doco about it >

Then – you can just call the following method within C# :

private static string PostYammerJson(string url, string accessToken)
{
    //make the request
    string json = null;
    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    request.Method = “POST”;
    request.Headers.Add(“Authorization”, “Bearer” + ” ” + accessToken);
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        Encoding encode = Encoding.GetEncoding(“utf-8”);
        StreamReader reader = new StreamReader(response.GetResponseStream(), encode);
        json = reader.ReadToEnd();
    }
    return json;
}

Within the C# code – I can then do this :

string postUrl = “https://www.yammer.com/api/v1/groups.json?name=CoolPeople&private=false”;

//replace with what you get from Yammer register App page

string accessToken = “1234567890qwertyuiop”;     

PostYammerJson(postUrl, accessToken);

This is a GREAT pattern – thanks to the folk at the Microsoft PnP on GitHub.

There’s a whole solution/project that does this – and a LOT more – great examples :

https://github.com/OfficeDev/PnP/tree/master/Scenarios/Provisioning.Yammer

🙂

Office 365 SharePoint Site Templates

When creating a new site collection within O365, you can choose the default (RootWeb) template to use.  

Most of these are the same as SharePoint2013 – but there are a few slight differences.

image

The easiest way to check the site template ‘name’ for use in PowerShell is actually to use the F12 developer tools – and view the HTML – neat trick !

image

For reference, I’ve made a list of all of them below.

Collaboration

  • STS#0 – Team Site
  • BLOG#0 – Blog
  • DEV#0 – Developer Site
  • PROJECTSITE#0 – Project Site
  • COMMUNITY#0 – Community Site

Enterprise

  • BDR#0 – Document Center
  • EDISC#0 – eDiscovery Center
  • OFFILE#1 – Records Center
  • EHS#1 – Team Site – SharePoint Online configuration
  • BICenterSite#0 – Business Intelligence Center
  • POLICYCTR#0 – Compliance Policy Center
  • SRCHCEN#0 – Enterprise Search Center
  • SPSMSITEHOST#0 – My Site Host
  • COMMUNITYPORTAL#0 – Community Portal
  • SRCHCENTERLITE#0 – Basic Search Center
  • visprus#0 – Visio Process Repository

Publishing

  • BLANKINTERNETCONTAINER#0 – Publishing Portal
  • ENTERWIKI#0 – Enterprise Wiki

Hopefully that helps someone out there – it certainly made sense for me – as it was missing the CMSPUBLISHING#0 which is the normal SP2013 “Publishing” site.

🙂

SQL Azure, error when editing stored procs

I have a SQL Server database within my Azure tenant, but I’ve been unable to edit any Stored Procedures – or view the list of procs.

The message I get is “unknown property IsNativelyCompiled”.

image

There are procs in there – I can execute then, or see view via SP_HELPTEXT – but not within Enterprise Manager (Management Studio).

This is within SQL Server 2014 (Management Studio – just the client tools on my Win8.1 PC)

image

It turns out there’s a SP1 for SQL2014 – which also updates the client tools.

Refer to this blog, for the various SQL build versions.

Unfortunately, the SP1 has been pulled – doh.    (At time of writing).   

For now, I’ve installed SQL 2014 CU6 – which is 640MB !

I can now view the list of Stored Procedures – and edit/update – phew !