Office 365 Unified API session from Microsoft Recoder 2015

MS-RECODER-540x270-Tweet_thumb.jpg

About the event

Recoder 2015 was a free one-day conference for application developers and IT professionals who wanted to get the fast track on Office 365.

My session

Intro to Office 365 Unified API

Over recent years Microsoft has been busy resetting the traditional developer landscape and in this session Wes will be introducing you to the exciting new Office 365 Unified API model and helping you to understand the APIs architecture and what choices or decisions you need to consider when approaching a development project in today’s Microsoft world.

Here are the slides that I presented during my session.

This was part of the introduction sessions so was super high level. During the short live demo I used the following API Explorer site.

https://graphexplorer2.azurewebsites.net/

This site allows you to prod and try out all the code snippets from the deck. When you first log in you will be asked to trust the app to all your Office 365 services. Then you can begin to call the various endpoints via the REST syntax.

Speaking at Microsoft Recoder 2015

MS-RECODER-540x270-Tweet.jpg

About the event

Recoder 2015 is a free one-day conference for application developers and IT professionals who want to get the fast track on Office 365. Discover how you can work smarter now, and get ready for the big innovations that are on the horizon.

Office 365 has become Microsoft’s fastest growing multi-billion dollar business, with hundreds of millions of users. At Recoder 2015 you will learn how you can build on this success – tapping into the secrets of the O365 APIs. There are very exciting times ahead, as Microsoft transforms the popular O365 productivity suite into an open platform running on all of the major operating systems, including Windows, Apple iOS and Google Android.

Recoder 2015 offers a fascinating day, whether you are an app developer looking to incorporate O365 functionality in your own apps, a developer creating full applications for O365, or an IT Pro responsible for the deployment and management of O365 applications.

See the UK’s first Live Demo of SharePoint Server 2016

In the morning you’ll gain new insights from some exciting keynote speakers including Steve Smith from Combined Knowledge (demoing SharePoint 2016 for the very first time in the UK) and Simon Hill from Wazoku, who will be sharing their views on the future of productivity and collaboration rooted in the reality of today. The afternoon is dedicated to breakout sessions tailored to IT Pro’s who deploy and manage the apps, plus Introductory and Deep Dive technical workshops for Developers, delivered by some of the industry’s most respected MVPs including Chris O’Brien, Spencer Harbar, Waldek Mastykarz and myself.

My session

Intro to Office 365 Unified API

Over recent years Microsoft has been busy resetting the traditional developer landscape and in this session Wes will be introducing you to the exciting new Office 365 Unified API model and helping you to understand the APIs architecture and what choices or decisions you need to consider when approaching a development project in today’s Microsoft world.

Registration

It’s free to attend, but registration is mandatory.

You can register at http://aka.ms/Recoder2015

We have capacity for 300 and we are expecting a sell-out.

SharePoint Evolution Roadshow 2014 session If apps are the answer what was the solution

SP Evo Conf

Wednesday June 11th saw the SharePoint Evolution roadshow roll into Cambridge. Bringing with it the weather Smile and a collection of SharePoint experts from around the globe.

The full days agenda can be seen here: https://www.sharepointevolutionconference.com/abstracts.html#camt1

My session kicked off the days ‘Technical’ track. The session described the evolution in thinking required when you move from the traditional SharePoint full trust solution model towards the SharePoint App model. Having been working with SharePoint apps since the pre-release program of SharePoint 2013 the session aimed to share my experiences and lessons learnt around the solution design approaches. The slides from the session are below.

 

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.

SPC125 – Hybrid and Search in the Cloud – Brad Stevenson

SPCLogo

Brad Stevenson talks about creating a search experience which spans an On-Premises and Office365 SharePoint 2013 environment.

Search in the cloud

 

So what is the story about the cloud search capability?

Comparing SP2010 online to SP2013 online

 

Area

2010

2013

Crawl Freshness

1-2 hours <15 minutes

Query Latency

good better

Scale

was limited now much greater

Manageability

was limited more extensive

User Experience

ok big UX improvements

Extensibility

very little some new stuff

 

  • Crawl freshness is important for any search system as its important that a user trusts the results they are given. Part of this trust is that they are seeing the latest content within a timely window.
  • Query latency is already really quite snappy in SP2010 online. SP2013 moves to client side rendering approaches to improve this snappiness perception even further. This approach allows the server to share some of the rendering load with the client device improving performance for the end user.
  • Scale in SP2013 originates from the FAST technologies so brings those benefits to bear, making it a powerful and scalable platform solution.
  • Manageability within SP2013 allows more control over the schema, examples are the control over managed properties and result sources. A lot of the features which were part of the service application have now been brought down to the site collection and tenant administration levels.
  • User Experience is dramatically different with new capabilities such as hover panels, visual refinements etc. This helps a user to establish the relevance of a result without leaving the results page or downloading the documents.
  • Extensibility is improved without writing code with such elements such as the rendering templates replacing the complex XSL.

Search extensibility in the cloud

 

No code:

  • Managed properties
  • Result sources
  • Query rules
  • Result types
  • Display templates
  • Dictionaries (via the Term Store)

Code:

  • CSOM
  • REST

Packaging:

  • Import/Export search settings
  • SharePoint apps

You manage your ‘global search’ via the tenant admin interface. The only major piece of the service application settings you have no control over is the crawl scheduling. In a multi-tenant environment this really makes sense.

Journey to the cloud

 

Definition of the cloud?

 

  • Public cloud – Office 365, allows you to focus on just the software services.
  • Private cloud – Windows Azure, allows you to offload the OS and hardware to the cloud provider.
  • Traditional – All managed by the internal organisation

Moving to the cloud

 

What to move? (not just everything) and should it be everything including customisations and settings.

When to move it? How do you plan the move? Is it an all or nothing or staged co-existence.

How to move it? What tools are available?

The migration lifecycle

 

Early – 90% on-prem 10% cloud

Mid – 50% on-prem 50% cloud

Late – 10% on-prem 90% cloud

How hybrid search can help

 

User want to easily find content, they just want to find things they’re looking for and not have to think about understanding the systems structure. It is about getting their job done efficiently.

Users don’t care about migration. So don’t force users to track what’s being moved and when.

Realise that most users will never move EVERYTHING to the cloud.

Hybrid Search User Experience

 

Demo environment details:

  • On-Premises SP2013 crawling a mixture of SharePoint data and file shares
  • Office365 indexing all of its content
  • Firewall between

So the idea is that from within either environment the user can get results from either. They use query rules to ‘cross-pollinate’ results from the other environment as a block of results. Personally I’m not sure this is a great user experience. It gives a false impression to a user of which results are most important. So I remain to be convinced about using result blocks.

A neat thing to know is that the refinement panel operates over ALL returned results rather than just the local SharePoint items. Also the hover panels are dependant on the sources WOPI configuration.

Configuring Hybrid Search

 

Configuration steps:

  • Choose one-way or bi-directional
  • Deploy and configure pre-reqs
  • Configure search data settings
  • Configure search UI settings

If you are early on in your migration lifecycle a one-way where on-premises indexes Office365 might suit your needs. Or late on a one-way works for Office 365 to use on-premises. Mid-life is definitely bi-directional where the experience should be the same.

Environment Configuration

 

image

One-way or Bi-directional

 

Where will users go to search?

  • Just on-premises
  • Just Office365
  • Both

Hybrid pre-requisites

 

Non-SharePoint:

  • Reverse proxy and certificate authentication
  • Identity provider (ADFS or Shibboleth for Office365)
  • MSOL Tools
  • SSO with Office365
  • DirSync

SharePoint:

  • New SharePoint STS Token signing certificate
  • Configure a trust relationship between SharePoint on-premises and ACS
  • Configure secure store
  • Configure UPA

Configure Data Settings

 

Result source (equivalent to a federated location and scope in SP2010) pointing at:

  • URL of remote location
  • Secure Store (for client certificate)

Configure UI Settings

 

  • Query rule to show remote results in ‘Everything’ tab
  • Search vertical which ‘only’ displays results from remote location (Office365 or on-premises)

Search Centre On-Premises: Data Flow

 

image

Scenario One:

User logs into on-premises and issues a search query. It actually issues two queries. First is to the local on-premises index. The second is issued to Office365. The second query is issued through the CSOM endpoint within Office365. Identity mappings take place where the on-premises identity is mapped to the Office365 identity. Office365 then performs the query and issues the results response.

Search Centre in Office365: Data Flow

 

image

Scenario Two:

Basic flow is a reverse of on-premises except there is the introduction of the revers proxies at the perimiter to route the request back to the on-premises SharePoint. Identity is mapped from the Office365 user to the on-premises user.

This means that in both scenarios there is correct data security trimming.

Beyond the Basics

Design considerations

 

What did Microsoft consider when designing the Office365 service:

  • Crawl versus Query – Chosen to go the query root as the crawl infrastructure within Office365 was limiting. Also hundreds of thousands of tenants need to have a consistent performance maintained. Query helps to provide the best and most consistent user experience.
  • UI Presentation – Users felt it was really important to see all the results on the same page. They didn’t want to have to switch between different pages. (I’m not sure I agree with this UX being the most optimum, users are used to choosing the ‘type’ of data they want on Bing/Google eg. Images/Shopping etc)
  • Relevance and clicks – Search learns over time. Search watches which results are clicked for specific queries and adjusts over time.
  • Background compatibility – Should provide other MOSS and SP2010 on-premises hybrid. This was not possible due to some significant infrastructure and services which would have required significant investment in extending the previous SharePoint versions. One major element was the challenge of identity mapping.

Alternative Hybrid User Experience

 

The demonstration showed the example of a glossary. This is stored in a SharePoint list on-premises. It is very useful information, but is not something users query for all the time. From on-premises the demo pulls ‘people’ results from Office365 via a dedicated search vertical.

To get the on-premises ‘people’ page to use the Office365 profiles it is as simple as pointing the web part settings to use the remote result source. This means when the users click the people results it goes to the Office365 profile page. Question is what happens to the links to people in normal item results?

Hit highlighting works.

Question about multiple people stores. Answer was the suggested best practice is to host in just one location.

Result Click-Through: Options

 

image

For users on-premises accessing on-premises links are fine. Once the user is on the Office365 search results the results now have internal only urls. The click through doesn’t route through the reverse proxy anymore. So users must have that external access to the internal system.

One solution is to have a VPN or Direct Access or leveraging the reverse proxy for url re-writing.

Microsoft recommend using VPN or Direct Access as it is easier to maintain over time.

The WOPI previews are operating where-ever the content is being served from.

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.

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.

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.

Configure VSIX project to enable debugging

DebugVSIX

Visual Studio 2010 beta 2 SDK includes the new extensibility project which produces a VSIX package. While developing these projects it is often helpful to debug the code. In some circumstances the debug settings can be lost so follow this post to add them back into the project settings.

To setup the VSIX for debugging:

Open the project properties window and select the Debug tab.

Select ‘Start external program’ and add C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe (assuming you have installed VS to the default location)

In the ‘Command line arguments’ add /rootsuffix Exp to use the experimental Visual Studio instance.

Properties window

Now when F5 is run Visual Studio installs the extension to %UserProfile%\AppData\Local\Microsoft\VisualStudio\10.0Exp\Extensions\ and opens it in the experimental instance.