SP.RequestExecutor cross domain calls using REST gotcha

CrossDomain

Recently I was building a prototype SharePoint hosted app to add items into the Host web. The basic operation of the app is that it queries the Host web for specific list types, then allows a user to add a collection of new items to the selected list. So read and write operations.

When dealing with the Host web it is important to remember that you are then subject to ‘cross domain’ calls and the restrictions in place for them. The browser protects users from cross site scripting and specifies that the client code can only access information within the same URL domain.

Thankfully SharePoint comes with some inbuilt options for these calls. The Cross Domain library is the primary option in either JSOM or REST forms.

I’ve been leaning towards REST mainly at the moment primarily as a focus for learning so I could get used to this method of data interactions.

So the first code sample is to get the host web task lists:

NB: This is a cut down extract of the function just to highlight the core request.

var executor;

// Initialize the RequestExecutor with the app web URL.
executor = new SP.RequestExecutor(appWebUrl);

//Get all the available task lists from the host web
executor.executeAsync(
{
url:
appWebUrl +
“/_api/SP.AppContextSite(@target)/web/lists/?$filter=BaseTemplate eq 171&$select=ID,Title,ImageUrl,ItemCount,ListItemEntityTypeFullName&@target='” + hostWebUrl + “‘”,

method: “GET”,

headers: {  “Accept”: “application/json; odata=verbose” },
success: successHandler,
error: errorHandler
}
);

Note from this sample how the host and app web urls are used within the url combined with the SP.AppContextSite. This is the key to invoking a cross domain call in REST using the SP.RequestExecutor

The second snippet of code is the one which adds the new item to the host web list:

NB: This is a cut down extract of the function just to highlight the core request.

var executor;

// Initialize the RequestExecutor with the app web URL.

executor = new SP.RequestExecutor(appWebUrl);

var url = appWebUrl +
“/_api/SP.AppContextSite(@target)/web/lists(guid'” + hostWebTaskList.Id + “‘)/items?@target='” + hostWebUrl + “‘”;

//Metadata to update.
var item = {
“__metadata”: { “type”: hostWebTaskList.ListItemEntityTypeFullName },
“Title”: item.title,
“Priority”: item.priority,
“Status”: item.status,
“Body”: item.body,
“PercentComplete”: item.percentComplete
};

var requestBody = JSON.stringify(item);

var requestHeaders = {
“accept”: “application/json;odata=verbose”,
“X-RequestDigest”: jQuery(“#__REQUESTDIGEST”).val(),
“X-HTTP-Method”: “POST”,
“content-length”: requestBody.length,
“content-type”: “application/json;odata=verbose”,
“If-Match”: “*”
}

executor.executeAsync({
url: url,
method: “POST”,
contentType: “application/json;odata=verbose”,
headers: requestHeaders,
body: requestBody,
success: addPrimeTasksToHostTaskListSuccessHandler,
error: addPrimeTasksToHostTaskListErrorHandler
});

Ok so at this point you’re probably wondering what is the gotcha mentioned in the title. Well here it comes and it’s one of those cut and paste horror stories which costs developers all over the land huge amounts of wasted effort.

So if you take a look at the following block of code

var url = appWebUrl +
“/_api/SP.AppContextSite(@target)/web/lists(guid'” + hostWebTaskList.Id + “‘)/items?@target='” + hostWebUrl + “‘”;

 

//TODO: find out why this works but the below fails with not actually performing the update
//$.ajax({
executor.executeAsync({
url: url,
type: “POST”,
contentType: “application/json;odata=verbose”,
headers: requestHeaders,
data: requestBody,
success: addPrimeTasksToHostTaskListSuccessHandler,
error: addPrimeTasksToHostTaskListErrorHandler
});

You’ll notice i copied over the structure of the method from a normal $.ajax call. THIS IS MY MISTAKE!!!!

As with many things the devil is in the details. By using this ajax snippet I’d introduced a bug which took nearly 4 hours to work out (very little found on the popular search engines about this). The worst part is that the call fires and comes back with a 200 success and even enters the success handler, BUT the action is not performed.

So what is the cause? Well basically there are subtle differences in signature.

  • The ajax call ‘type’ should be ‘method’ in the SP.RequestExecutor
  • The ajax call ‘data’ should be ‘body’ in the SP.RequestExecutor

So there you have it, two word typo’s which throw no errors but cause a logical failure in the code.

I hope this helps someone else avoid the pain Open-mouthed smile

Some really useful information about this capability can be read at:

Chris’ app series covers using this library in anger – http://www.sharepointnutsandbolts.com/2012/11/access-end-user-data-in-host-web-from.html

Apps for Office and SharePoint blog article discussing the inner workings and options for cross domain versus cross site collection – http://blogs.msdn.com/b/officeapps/archive/2012/11/29/solving-cross-domain-problems-in-apps-for-sharepoint.aspx

Using REST in SharePoint apps – http://msdn.microsoft.com/en-us/library/office/jj164022.aspx

One final comment, MSDN Code has this sample: http://code.msdn.microsoft.com/SharePoint-2013-Get-items-7c27024f/sourcecode?fileId=101390&pathId=1361160678 which doesn’t really demo cross domain at the time of writing as it isn’t using the code correctly against the host web in my opinion.

Awarded Microsoft MVP 2013 for SharePoint Server

620MVP_Horizontal_FullColor

Literally minutes before leaving work on 1st  October I received the following email:

MVPEmail

This left me utterly speechless, which is not something that normal happens to me. After re-reading it about ten times the news finally sank in. I’m ecstatic that Microsoft have awarded me the MVP award for my contributions to the SharePoint community.

So I wanted to share a number of thank you’s for everyone who has supported me along the way.

Most importantly my beautiful wife who has supported my many many hours chained to my PC in the office at home beavering away on CKSDev or Presentations instead of snuggling up in front of a movie on the sofa. Without her understanding and support I definitely wouldn’t have found time to make the contributions I have. Also sitting through many hours of practice presentations before my speaking events.

Matt Smith for four years ago helping me to understand how to start to become involved in the SharePoint community.

Waldek Mastykarz for his friendship, support and advice and those midnight coding adventures before releasing a new version of CKSDev. Thanks buddy 🙂

Chris O’Brien for his friendship, advice and putting up with some seriously deep technical conversations over the years when I’m trying to get my head around a SharePoint feature and Visual Studio API.

The CKSDev team past and present, Wouter, Matt, Waldek, Todd, Paul, Carsten and Wictor who all at some point over the last few years have advised, written some cool code and generally helped ensure CKSDev was meeting everyone’s needs.

The event organisers for SUGUK, Evolutions/Best Practices London, SPSUK and SPSNL (Steve Smith and Combined Knowledge, Brett, Tony and Nick, Mirjam and the DIWUG peeps) for providing me opportunities to present and be part of the event teams.

My employers Content and Code and especially people like David Bowman and Tim Wallis who gave me time and support to contribute to the community. Not to mention Salvo di Fazio, Tristan Watkins and Ben Athawes.

To conclude what has been quite an emotional post to write I just want to say thanks to everyone in the community and MVP community who have helped me all these years. There are too many to list, but you know who you are 🙂

Yammer SharePoint App Installation Error

YammerError

Yammer and Microsoft released a new SharePoint app available in the Office Store here: Yammer App details

This is a great first step towards better Yammer and SharePoint integration Smile

However on installing it on some sites I encountered an error:

image

If this was an on-prem installation I’m sure the ULS would be giving some huge clues as to what is up, but I was lucky enough to be using Office365 (I love the fact bugs are Microsoft’s problem to diagnose Smile). So the only way forward was to raise Service Request. So after some problem investigation with the Support guy we got to the answer.

The key reason this App fails to install is the supported locales from Microsoft. As you can see from the screenshot below, only US English is a supported locale.

image

Ok so nothing massively unusual there? Nope in SP2010 this is the only English available, but with SP2013 Microsoft finally worked out the UK uses ‘proper’ English with all it’s quirky spellings for things like ‘colour’. So with this in mind all of our tenant site collections are set to UK English as the locale, as you can see in the screenshot below.

image

So when you add the app you think everything would be fine…. oh how wrong you’d be… So the add new app pops the ‘trust’ dialog. My first comment here is that it also includes the language options, so not really only about ‘trust’ is it.

image

Second bad user experience here is that the languages selection is hidden by default. So being a typical user I didn’t read the information and clicked ‘trust it’. And that’s when the install error happens.

So what should you be doing?

image

So the killer ‘feature’ is that the ‘Trust it’ dialog is picking up the current sites default locale (in this case English UK) and installing the app with that locale. Now if you remember the Yammer App only supports English US locale, so you need to select this locale from the dropdown.

image

So now the app is installing with its supported English US locale into our English UK sites. So our users get the language they want in most of SharePoint and Yammer works in it’s supported language.

image

image

I think this is pretty bad that it defaults to install in a locale it doesn’t support and provides no feedback to the user. So this experience is littered with badly designed UX and errors which would be very easy to avoid, and thus wasting the time of both the user and MS Support. Sad smile Lets hope someone fixes this in some later releases.

Further fixes and information can be found here: http://blogs.msdn.com/b/ragnarh/archive/2013/07/02/yammer-app-for-sharepoint-amp-office-365-tips-amp-tricks.aspx

I hope this saves someone the hassle of raising a ticket for something so simple.

SPSNL 2013 Presentation

SPSNL

Saturday 29th June saw the 2013 SharePoint Saturday Holland. Another great event organised with so many quality speakers and companies in attendance. It was a privilege to be invited to speak Smile

I presented a session on Apps for Office 2013 and SharePoint 2013, the slides can be seen below. I hope everyone found the session useful Smile I certainly enjoyed presenting to such an interactive audience.

I think Apps for Office is one of the coolest new features of Office and SharePoint 2013 and my session gives a really quick overview of the Apps for Office solution space. Then the hook up between SharePoint and Office that is now possible through the demo solution.

Over the next few months I’ll be publishing a dedicated series for Apps for Office so stay tuned for more soon.

Thanks to everyone who helped organise the event.

SharePoint Evolution Conference 2013

SPEvo13

SPEvo13

For five years running Combined Knowledge have hosted the conference and this years looks to be the best yet.

So why should you attend this conference?

For me the key reasons would be:

  • It will provide you with access to the best SharePoint experts from around the globe
  • You can learn about the latest version of SharePoint 2013 and its key features and applications across the different tracks
  • Meeting up with friends from across the SharePoint community
  • Listen to real-life implementations from the community track speakers
  • You get all the sessions on the DVD
  • The party is always amazing Smile

So if you haven’t already done so make sure you register soon to be in with a shout at one of the many prizes up for grabs. Register here

Speaker_Evo-2013-Banner

I’m lucky enough to be speaking at this years SharePoint Evolution Conference 2013 in London between the 15th and 17th of April 2013.

Bringing SharePoint information into Office through Office Apps

Audience: Developers

Office 2013 introduces new Apps for Office which allows developers to create apps which interact with Word, Excel and Outlook. Using an App for Office we can bring information from within the enterprises SharePoint platform and help users create documents and bring increased value form their SharePoint data. The session will explore some scenarios to bring SharePoint into the Office clients.

My Session is on from 9:45am – 10:45am on the Monday in the Pick and Mix track.

Hopefully I’ll see you there Smile

SPSUK Bring SharePoint into your Office with Apps for Office

SPSUK2012

Saturday 8th December saw the 2012 SharePoint Saturday at Nottingham’s Conference Centre. Another great event organised with so many quality speakers and companies in attendance.

I presented a session on Apps for Office 2013 and SharePoint 2013, the slides can be seen below. I hope everyone found the session useful Smile I certainly enjoyed presenting to such an interactive audience.

I think Apps for Office is one of the coolest new features of Office and SharePoint 2013 and my session gives a really quick overview of the Apps for Office solution space. Then the hook up between SharePoint and Office that is now possible through the demo solution.

Over the next few months I’ll be publishing a dedicated series for Apps for Office so stay tuned for more soon.

The code for the demo solution is available here.

The code is far from production ready and is used at your own risk.

SPC147 – Mastering app for Office Development – Ali Powell

SPCLogo

Ali provides a walkthrough of Apps for Office. Look at the type of shape and see some examples. Explanations of the API framework.

Mastering Apps for Office Development

Looking at various aspects that need consideration during development and design.

Trends impacting the apps we develop

Devices – increasing numbers projections of 350m smartphones in the workplace by 2016

People – 82% of world’s online population using social networking

Cloud – 50% of enterprises on the ‘road to’ cloud

Office is the most installed apps outside of anything in browser

New apps, New scenarios, New User Experiences

Devices – Fast and fluid with touch, pen, mouse and keyboard. Immersive experience (Win8). Support for different OS

Cloud – Office on demand, roaming and up to date. New cloud app dev model. Enterprise grade reliability and standards.

Social – Newsfeeds and micro blogging, extend with yammer. Pervasive social across Office. Multiparty HD video and Skype federation.

Office Mobile across platforms

The apps should work across all devices

Consumers typically have multiple devices

Apps are everywhere

They are becoming the primary way we deliver functionality to end users.

This is changing the paradigm about how we design and develop functionality. Old world apps were often composite applications which had a lot of breadth. They would have multiple tabs, screens and literally hundreds of different bits of functionality in one app.

Apps really give you the ability to give you transacted solutions which essential guide a user from start to finish for a specific task.

With this shift to much more targeted usage, our app lifecycles are vastly reduced as they need to deleiver less functionality and more targeted use cases.

It should reduce the need for 18-36 months projects before something is delivered.

A new paradigm for Solutions

Personas > (have) > Objectives > (and use) > Devices > (to consume) > Solutions > (composed of) > Services > (running on) > Infrastructure

Really now if you look at the flow above the solutions we are building are tied to personas. Those personas have the responsibility to meet some objective within your solution. They use devices and these devices consume the solutions we build. Most solutions will be consuming some kind of services, they often compose multiple services together into an app. This accelerates solution development by making better use of things already internally provide or from the marketplaces. All these services run on infrastructure, and the trend is to find infrastructure which is flexible and scalable.

Note: Tie an app solution to a specific end user persona to make them a success.

Apps for Office

Loosely coupled services with simpler contracts that enable developers access to more best of breed services in private and public clouds.

HTML5 and CSS3 are rapidly becoming the UX code paradigm.

Support the standardised identity model that spans computing devices.

End user focused, contextual, web based and discoverable.

Bring the web into Office.

What are apps for Office?

  1. Document-based manifest driven applications
  2. HTML5, CSS3, JavaScript
  3. Web applications hosted by any http delivery mechanism

Note: Apps for Office do not replace VSTO, they just give a different ability to deliver extensions.

Apps for Office Shapes

Task pane

Content

Mail

App for Office Framework

App for Office

Web Extensions Framework (wef)

Office JSOM

Application specific JSON (Outlook JSON, etc)

App API’s (third party api’s)

Rich clients / Web Browsers

App Manifest

Demo of the standard manifest.

Important bits of information from the manifest

  1. app type – which defines which shape this app is
  2. Id – is the unique Guid identifier which tells Office what your app is. This binds the app to the document or mailbox item its associated with. This Id is also the service point for upgrading the apps in the future.
  3. Version – the version of this app
  4. ProviderName – The name of the organisation who built the app
  5. DefaultLocale – The language for the default. This MUST be set if you want Office store validation to pass
  6. DisplayName – The name of the app
  7. Description – The description of the app
  8. AppDomains – ??
  9. Capabilities – Allows you to specifiy which set of functionality it depends upon within the host
  10. Default Settings
    1. SourceLocation – VERY IMPORTANT as it tells the Office Runtime which url it should load when the app loads within Office
  11. Permissions – The collection of permissions this document requires to be granted to run its functionality

Office stores the catalog information

In registry: Computer\HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Wef\Developer key can have a string key set for the manifest of the demo app

This helps during development without a catalogue location

App for Office Manifest

There are four pieces of information when building an app for Office are covered:

  1. Consumption Declaration – Means you need to make sure the capabilities your app depends upon, and that you have identified the type of app you want deployed. You can’t change the shape of an app once its been associated with an app.
  2. Capability Consumption – Defining which Office capabilities the app needs/
  3. Service Consumption – Identify the services your app needs to consume. Assert the client endpoints the app is going to consume. This is part of the ‘AppDomain’ definitions.
  4. Aesthetic Design – Make this an important piece, two things to make your app is installed. Make sure the first this is that the icon is a really good one. Then also consider how it sits alongside the Office branding.

Demo

Looking at an excel app for election tracker

Inside the OpenXML the app is referenced but not embedded

Open the ‘xl’ folder

Open the ‘webextensions’ folder

Open the webextensions.xml file

The xml contains some interesting nodes.

WebExtension Id – is the unique ID of that app

Reference

  • StoreType, OMEX is the public store, Registry would be a developer app, insternal would be internal app

Bindings – Shows the apps bindings to the content

Another interesting fact is that the last state of the app visually gets stored as an image in the document should the app not be available. This occurs when a save of the document is made.

Note: It would be interesting to see what the behaviour is around Versioning and Co-Auth in SharePoint hosted docs for this.

Open the ‘_rels’ folder

Open the webextensions.xml.rels file

This file binds the app instance and the image together within the document

Note: nothing is being installed to the local machine

Demo of this Excel app within the WOPI client which was pretty neat.

App For Office User Experience

App for Office execution is different on Client and WOPI.

Think this info was a little bit to deep and possibly to hardcore.

Apps are isolated, secure and performance boxed

Web client basically runs in an iFrame sandbox

Target capabilities by discovering your host – these become key to design. The developer should have intimate knowledge of what the target Office client can provide. So if it has been targeted to say Excel and Word that if a user opens it in Project that it detects this and gracefully exits.

Avoid the common pitfalls – JS Alerts are not fired. Apps for Office have governors in outlook which prevent you impacting the performance of Outlook.

Resource awareness – You don’t have all the resources from the host machine. The governors limit this. These will close the app if you breach the thresholds. In Outlook apps you can use REGEX but these have fixed time and CPUs before they are taken offline.

Crossing AppDomains – Sometimes this is needed, use AppDomains to tell the web extensions framework you will be doing this. If you don’t the resource will load in a new browser window, which isn’t probably what you want.

Resource sharing leverage Oauth – Make this default auth model. Identity is the responsibility of your app to require, acquire and maintain.

Give your app some style – Make it easy to follow, look nice and be creative.

Demo

Outlook VOIP Mail app

Demo’d the rules for a mailbox item

Apps for Office Scenarios

SharePoint Centric – Deployed as part of your SharePoint app as document templates so that they light up when you use that document

  • Business Process – Start a workflow from the document
  • Team Collaboration – As the user moves around the document supplementary information is brought back from SharePoint.
  • Workflow

Document Centric –

  • Data visualisation / Analysis & Mashups
  • Reference Tools
  • Contextual Content & Services
  • Content Authoring
  • Dashboards

Key Takeawys

Apps > (require) > Capabilities > (that target) > Hosts

One app can run across multiple clients and the cloud.

Mailbox centric apps for email and appointment features.

Task pane and Content apps for document centric apps.

More Information

JavaScript API for Office

http://bit.ly/UV2POY

Resource Usage Settings

http://bit.ly/116C8dy

Apps for Office XML Manifest

http://bit.ly/SomibV

Apps for Office Training

http://bit.ly/N76ZOC

Apps for Office Samples

http://bit.ly/V4zf87

Summary

Useful overview session. The different niche information to other Apps for Office sessions made this one worth seeing.

SPC136 – JavaScript Best Practices for Developing Apps – Scot Hillier

SPCLogo

Scot Hillier talks about leaving the developers with good solid ideas how to use and structure apps with JavaScript. The session purpose is to teach server side developers how to write JavaScript correctly, helps to introduce patterns to the apps in the new world.

JavaScript best practices

 

http://hillier.codeplex.com for the code

Coding practices

These are things to do good apps in the new model. It is important to establish these practices to make sure the apps that you build are easy to maintain and understand.

Strict mode

Declares using the "use strict" statement either at the top of a library or inside of a a function

Restrictions

  • Can’t use a variable without declaring it
  • Can’t write to read-only property
  • Can’t add properties to non-extensible objects
  • Can’t illegally delete functions and variables
  • Can’t define a property more than once in an object literal
  • Can’t use a parameter name more than once in a function
  • Can’t use reserved words, eval, or arguments, as names for functions and variables
  • The value of ‘this’ in a function is no longer the window object
  • Can’t declare function inside of statements
  • Can’t change the members of the ‘arguments’ array

Equality operators

Avoid coercive equality operators

==, != are coercive

===, !== are not coercive

Examples:

0 == ‘0’; //True
0 === ‘0’; //False
false == ‘0’; //True
False === ‘0’; //False

The problem with coercive is they try to work out what you mean, see the example where numeric 0 == text 0 is returned true. When this is not actually equals due to the data type.

This will save a lot of conversion bugs cropping up in code. (especially is C# is your background)

Encapsulation

Singleton Pattern – The declaration of a literal JavaScript object, which can have functions defined which can be invoked using method syntax.

Module Pattern – Self-invoking function ‘();’ at the end, the advantage is the public and private members to the object.

Prototype Pattern -Gives the developer a constructor, typically defining the member variables in the object. Then extend the prototype with the functions. The final element is the use of the ‘new’ keyword to create an instance with the prototype extensions.

If you need just one thing of something, then either Singleton or Module pattern are good. If you need a lot of something then the prototype is probably more appropriate. The prototype pattern is also more efficient, it will use the function on the prototype for every instance.

Promises

This becomes an important area of focus as a lot of the operations in apps are run asynchronously.

The reality for business apps is that multiple calls are going to be placed. So this is nowhere close to the hello world example of one call and one pair of methods to handle success and fails. This can lead to lots of nested calls. The second call relies on information in the first call, and can’t be made until it is retrieved.

Basically a ‘promise’ makes an async call but immediately returns an object, this object can be held and is the ‘promise’. This object then becomes filled with the data when it is returned. This object can also be held onto beyond the call which provides and interesting option for caching.

Also called ‘deferreds’

Simple async operations

The whole point of these is to avoid lots of spaghetti code.

Basic code pattern:

function myPromise() {
    var deferred = $.Deferred();
   
    setTimeout(function() {
        deferred.resolve("success");
    }, 1000);
   
    Return deferred.promise();
}

myPromise().then(
    function(value) {
        alert(value);
    }
    function() {
        alert("error");
    }
};

This is a jQuery example

jQuery offers the developer a $.Deferred function

The returned object in the first code block is within the developers method but it returns the jQuery object

The promise object has an implementation in the ‘then’ method

This function takes two function as args, the success and failure functions.

You can see from the code the removal for the need to nest calls and code.

So this is the basic approach, to take a deferred object and return it immediately, when things succeed, you call the resolve method of the deferred object. So this object will also hold the data, so there is no need to go back to the data source if the object data is already collected. This could be really useful when you think about people profile objects.

Demo

From the ‘Remote Endpoint App’

The example calls one RESTful endpoint for the album info and a second for the album art

Showed how in the app manifest the ‘remote’ endpoints were specified. These are cool because they allow the server to make the call to that endpoint for you.

If you are connecting to SP stuff or the SP host web you ask for permissions to do this during installation. Apps in SP are first class principals in SP2013, people authenticate with claims, apps use OAuth

This is one example for making a cross-domain call, when you specify a remote endpoint in the manifest for the app the call is actually made by SharePoint. So it’s made on the server side, the results are then relayed to the app. This is neat as it means the call is no longer cross domain.

In the musicbrainz.songquery.js file there is an example of calling this declare RESTful endpoint

Note: If you think you might be calling libraries which might not be using ‘use strict’ then put it in your function instead of your library.

To make this call through SP you have to use the ‘SP.WebRequestInfo()’

The code actually making the call to execute the code above is in ‘musicbrainz.songviewmodel.js’

Interesting observation that all the deferred objects are kept in an array

In the load function the code checks to see if the code has already been executed

The code matchs on the artist names in the held promises

If it was found the code sets the active promise to the one found

Be careful to use the ‘new’ keyword to make sure that instances are created or the code would go a little bit mental.

It then calls the ‘then’ method on the active promise

This block contains both success and fail logic

The patterns are really nice as the endpoint interactions are in a very clean library. This is really focusing this code on just the call, the display logic is factored out away from the data call. Really very well done, as you would in the C# world of MVC or MVVM

Note: Rob Bouge is building a ‘promise’ library over the SP REST calls

Libraries

Segregate code into libraries, there is a balance, due to efficiency of download, so maybe some go back together to make them faster to download.

Note: there is probably something for CKSDev as a feature for this

Minify those libraries so they download a lot faster, there are tools to do this

Consider the use of a CDN, how they get to the end user, a CDN is better for versioning

Load the SP libraries dynamically

Example code:

$(document).ready(function () {

hostweburl =
    decodeURIComponent(
        getQueryStringParameter("SPHostUrl")
    );
   
appweburl =
    decodeURIComponent(
        getQueryStringParameter("SPAppWebUrl")
    );
       
var scriptbase = hostweburl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js", onSuccess);
   
});

This is a good technique to get the SP libraries

Demo

Code is in ‘ContactsApp’

Note: the App project has a file called _references.js which is used to reference the scripts and get intellisense from the library

So the intellisense comes from this references file but the actual page references the debug versions

App Best Practices

REST

REST
This is the approach for web services
Uses a URI to completely specify the operation

OData
Maps CRUD operations to HTTP verbs GET, POST, PUT, DELETE, PATCH
Odata is an implementation of RESTful principles

Recommendation is JavaScript against REST and MVVM for on-premises and cloud

Second option is MVC4 and c# client side object model approach for those who don’t want to learn and write JavaScript. This of course means using provider hosted apps, which are more complicated.

_api replaces _vti_bin/client.svc

Two main ways to make RESTful calls

    1. $.getJSON – is a simplified way to make a RESTful call, normally one liner and returns a JSON object. This object has the kind of dot properties C# developers will like. This makes much more sense than returning just XML as it doesn’t require parsing into something useful.
    2. $.ajax – This is mainly just a longer version of JSON. Note the header is "application/json;odata=verbose" which not all examples will give but is best to use. If you don’t get this right the server will fail the request.
   
Basically as a REST programmer the entire focus is on the correct URI for the data

Note: a cool endpoint to return the viewing user is ‘/_api/web/currentuser’

Model-View-ViewModel pattern

Model contains data

View presents the data

ViewModel binds the Model and the View

The purpose is to separate the display from the data collection.

It works really well in JavaScript

The ViewModel fills the Model with data and then sends it to the view for display.

The best way to implement this is to use a third party library

Knockout.js http://knockoutjs.com

Features declarative bindings between elements in the code and pages (like old skool data binding) and dependency tracking

Pointed out the cool thing is the ‘ko.observableArray()’ which is the data and changes will trigger a page redraw

App UI guidelines

App project template – The VS template will already have some SP feel

WebTemplate – Apply a template

Chrome control – If just html page is being used, so use the chrome control

Custom Branding – Roll your own styling

Summary

This session had some useful patterns that can be recognised from some of the server-side patterns used in traditional SP development. The session left a lasting impression about the importance of well structured app JavaScript and what benefits it could bring to the developer.

SPC046 – Creating apps for Excel, Word and PowerPoint – Rolando Jimenez

SPCLogo

Rolando introduces the new investments by Microsoft for Apps for Office. This session is a deep dive into how to create apps in Excel, Word and PowerPoint.

Common App Architecture

 

The diagram shown highlights the architectural structure of the app model. The Office 2013 also contains a client side API. This allows apps to interact with the office content.

The session focus is on the client side logic so the:

App containing the HTML/CSS/JavaScript
Office JavaScript

Apps for Office – Recap

Web Page + App Manifest = App

Core concepts

  • 3 shapes, Task Pane, Content and Mail shape
  • Multi-platform and Cross App
    • Excel (web/desktop)
    • Outlook (Web/Desktop/Mobile Web)
    • Word (Desktop)
    • PowerPoint (Desktop)
    • Project (Desktop)
  • JavaScript API
  • Runtime sandbox

It is important to note that Apps for Office are agnostic to its host and is a core principle.

Principles

Cross Platform – designed from the ground up, providing abstraction, is async. Microsoft have not ported the old APIs (COM or .Net) into JavaScript they have built this from the first principles.

Cross App – common objects and methods across apps (selection, tables, settings) Principle is to present the office suite to a developer consistently and not really concern them whether they are in Word or PowerPoint. A selection is a selection.

Compatibility -Office version to version

Web standards – ECMAScript 5 e.g. Property get/set, strict mode, plain JS objects

Performance – async, limits. Things will be shut down which sap performance

Office JavaScript API Overview >

The diagram shows the hierarchy

  • Office.context
    • Document
      • R/W selection
      • Bindings
      • Settings
      • CustomXmlParts
    • Mailbox
      • Item
      • User Profile
      • EWS
      • Properties & Settings
    • Project
      • Project Info
      • Tasks

This session will focus on the ‘document’ branch of the API

Demo

Basic Hello World example

Choose App for Office 2013 in VS2012

Demo app selection was all the Task Pane options

In the VS solution the Office App project is the top one, with the manifest file inside

Pressing F5 before any changes should run a working default code app

In the html there is a JS include for

<script src="../Scripts/Office/1.0/office.js"></script>

Which means the Office API is being included

But be aware that this file is actually on a MS CDN and this is actually commented out by default. So good practice is to change to use the CDN version. This will mean that as the API gets updated your app will get them.

The first step is to create the ‘Office.initialize’ function

This function is the runtime handshake, and the app will error if it is missing

For Excel, Word and PowerPoint the document object is the most important object to start from

To change the run client you can change the ‘start action’ to the client you want

You can change the type of data you can interact with you use the ‘coercionType:Office.CoercionType’ which allows you to set things like html, openXML etc.

During the demo Rolando used a snippet of html for bold text, enetered it into the task pane app and set data pasted it into the doc as bold text. Proving the API can interpret the html into the document.

Note: You can change the html during debugging if you just click save and F5 in the app window

Demo of the OpenXML and its power

This is very useful where you have complex information content.

Org chart example showed how the app can interact with OpenXML to fill an orgchart form data in the app

Bindings Example

Bing map example bound to the data

The project is a Content app

Used the OOTB Bing Map scripts

Technique: In Office Apps the JavaScript ‘alert’ has been suppressed so as a developer you need to implement somewhere to show messages and debugging markers.

Note: the selection supports text/matrix and tables

Demo showed a basic map insertion and setting pins on the map based on selection of cells

To add a binding to the document call into the ‘Office.context.document.bindings’ object

To have the content app react an event handler needs registering

This can then react and make the app change based on whether data or selections have changed.

Settings example

Code example:

_doc.settings.set("mode", _mode);
_doc.settings.saveAsync();

Which persists the mode setting of the app into the document.

Technique: think about this state persistence for you apps, as a usability aspect it would be important

Custom XML Parts

A hidden and powerful feature in Office

These were introduced in 2007, documents can store islands of xml data, these are called custom XML parts within a document file.

Content Control Binding to parts

Word has content controls, these have been around since 2007 , these controls act as containers for specific kinds of content. Content controls can be mapped to nodes within the custom XML part.

There is now a new repeating section content control. This control provides the capability to bind to a collection of nodes.

Note: How to enable the Word developer tab, Backstage >> Options >> Customise Ribbon >> Right hand list has the ‘Developer’ and check it.

The developer tab allows the viewing and editing of the XML mapping pane

You can add a new part from that task pane.

Once the content is inserted into the xml mapping pane, you can right click and choose ‘insert content control’ and select the type of control you need.

Word also now has a repeating content control. So you can create a table, insert values from the XML and then highlight the entity and insert a repeating control to make it repeat for the length of the entity array.

Of course the example was done manually, but it can be done via the app code as well. This becomes powerful to embed data into the document.

Example used was an invoice document bringing in the data from another service. This is a very cool use case.

Operations that can be performed

  1. Add/Delete custom XML parts
  2. Get XML parts
  3. Get/Set node values
  4. Event handlers for node deleted, inserted, or replaces

Core objects for working with custom XML parts

  1. CustomXmlPart
  2. CustomXmlParts
  3. CustomXmlNode
  4. CustomXmlPrefixMappings

Connecting to SharePoint

How Apps for Office relate to SP

Now that Office365 contains Office, Exchange and SharePoint developers can now take advantage of this to create very complex solutions which span these technical capabilities.

Example is a simple task pane app which works in Word or Excel called ‘SPLister’

What this demo app does is allow the selection of any table that exists in the document, and then automatically generate a SharePoint list of it.

A key note is that the app needs to be told the SP url

The demo app is running from Azure so it will need to get into SP via Oauth

When invoked SP realises and asks the user to trust that app via Oauth consent flow page

Once SP issues the app with its access token it can start to communicate to the app.

The app is using the client side OM to create the list.

The demo app has both client and server side code. This was a little frustrating as it would have been great to see this being a JavaScript only hosted app.

Showed the ‘Seller Dashboard’ and the client ids

The ‘client id’ is the id which allows you permissions to request access to SharePoint in Office365

Code example for initialising the authentication to SharePoint.

function initAuthFlow(siteUrl, inSameWindow) {
authorizeUrl = siteUrl + "_layouts/15/OAuthAuthorize.aspx?IsDlg=1";
authorizeUrl += "&client)id=" + $("#clientId").val();
authorizeUrl += "&scope=Web.Manage";
authorizeUrl += "&response_type=code";
authorizeUrl += "&redirect_uri=" + $("#redirectUrl").val();
authorizeUrl += "&state=" + siteUrl;

if (inSameWindow) {
//Perform authorization flow in this window
window.location = authorizeUrl;
} else {
//Open a new window to perform the authorization flow
authWindow = window.open(authorizeUrl, "authWindow");
codeListener(); //Start listening for the auth code
}
}

This code will start the auth request, this allows the permission. The client id provides the identifier for the calling app. The code also requests the permissions it needs on SharePoint. The code asks for the auth code in the url and provides the call-back redirection url to send it too.

The example app has the handling logic for the returned auth code in the C# code behind of the aspx app page. The ‘TokenCache’ and ‘TokenHelper’ classes are used to handle storage of the returned token to reduce the need to keep asking for it.

Functional areas v’s App support summary

 

Functional area

Word

Excel/Excel WAC

PowerPoint

Outlook/OQA

Project

Get/Set data as text, table, matrix

X

X

X

X

Settings

X

X

X

X

Get File

X

X

Bindings

X

X

Custom XML Parts

X

Html and OOXML

X

Mailbox

X

X

Resources

http://dev.office.com

Summary

A good overview into the power of Apps for Office. It was disappointing that the question of how to host them within SharePoint (not AZURE) remained unanswered. I’m guessing that an ‘auto-hosted’ SharePoint app might be the answer, but only some trial and error will confirm that.