Deep Dive Office 365 API for SharePoint Sites service

Yesterday another DIWUG event! This is a monthly community event in The Netherlands. Albert-Jan Schot (Appie) did a presentation on the Office 365 Groups and I presented a session about the Office 365 API for SharePoint Sites service.

You can find my slide deck on SlideShare, http://www.slideshare.net/bramdejager/deep-dive-into-office-365-apis-for-sharepoint-site-services.

All demos together resulted in a single code base which you can download here.

Developing hybrid SharePoint apps that run on-premise and in the cloud – ESPC 2014

My session at the European SharePoint Conference (#ESPC14) was around developing hybrid apps with the SharePoint App Model. Below you can find the slide deck and PowerShell scripts I used during the demo.

Before you start building hybrid apps who are depending on the authentication done by Azure Control Services (ACS) you need to setup a trust between your on-premise farm and ACS.

  1. Replace the default STS certificate and reboot machine afterwards (Replace-STSCertificate.ps1)
  2. Install Microsoft Online Services Sign-In Assistant for IT Professionals RTW (64-bit), http://www.microsoft.com/en-us/download/details.aspx?id=41950
  3. Install Microsoft Online Services Module for Windows PowerShell (64-bit), http://go.microsoft.com/fwlink/p/?linkid=236297
  4. Run script to connect on-premise SharePoint farm to ACS (Connect-SPFarmToAAD.ps1)

Some important side notes:

  • When replacing the STS certificate, all current trusts who are depending on the STS become invalid. Meaning you have to recreate your existing Trusted Security Token Issuers (Install-TrustedSecurityTokenIssuer.ps1 & Remove-TrustedSecurityTokenIssuer.ps1)
  • Ensure you are using the RTW version of Microsoft Online Services Sign-In Assistant instead of the BETA (which is linked in the TechNet article)

Download PowerShell scripts.

Scripts originate from How to: Use an Office 365 SharePoint site to authorize provider-hosted apps on an on-premises SharePoint site (http://msdn.microsoft.com/en-us/library/office/dn155905(v=office.15).aspx), I don’t own the scripts but only provide them for easy of use.

Develop, Build, Package and Deploy Apps for Office 2013 with Visual Studio 2013–European Office 365 Connect

On April 1st and 2nd in Haarlem (The Netherlands) the first European Office 365 Connect took place. Speakers from over the world (like Dan Holme, Seb Matthews, Marc Reguera and many more) visited Haarlem and did sessions related to Office 365.

I’ve done a session about Apps for Office together with Visual Studio 2013. This was a kind of follow-up session for “The New SharePoint Online Apps – Napa in Action” from Patrick Lamber. You can find my slide deck below.

The demo was around building a Wikipedia Task Pane app which leverages the Wikipedia API for searching Wikipedia. Below a screenshot of the Task Pane App for Office inside the Word 2013 (desktop) client.

Wikipedia Task Pane app inside Word 2013 client

Once the app was done it’s deployed to Windows Azure via a Web Deploy package and the XML manifest is made available to end-users to consume from the Corporate Catalog (hosted in SharePoint Online). After configuring the Office client the Corporate Catalog is available from within Word, Excel, PowerPoint.

Apps for Office catalog in Word (desktop) client

Download the demo sources here: http://1drv.ms/1pTuGx9

Speaking at the European SharePoint Conference 2014

In case you missed it, the European SharePoint Conference 2014 programme is now available and I’m delighted to announce that I am speaking at Europe’s largest SharePoint event in Barcelona, Spain from the 5-8th May 2014.

I will be conducting a session on “Developing Hybrid SharePoint Apps that Run On-Premise & in the Cloud” aimed at Developers.

“Developing Hybrid SharePoint Apps that Run On-Premise & in the Cloud”

"With the new SharePoint App model running outside the SharePoint worker process it introduces new authentication models. As a developer you don’t want to build multiple versions of the same app implementing each authentication model separately. This session explains the differences between securing SharePoint apps with OAuth in Office 365 and S2S High Trust in on-premise deployments. You will learn how to build a single app that will run on-premise, online and hybrid SharePoint environments.”

clip_image002

The European SharePoint Conference will be run over four days and will feature over 100 informative SharePoint sessions and 6 preconference tutorials providing you with a fantastic opportunity for learning and building your SharePoint skills. Check out the full Conference Programme to see all sessions and topics that are being covered by myself and world renowned SharePoint experts.

If you want to deepen your SharePoint expertise, to understand the trend of the SharePoint market, and to learn how to leverage Microsoft Office 365 for your business, including the revolutionary Enterprise Social wave, the European SharePoint Conference is the best place to be in 2014!

Prices start as low as €995! There is also special group discounts for bookings of 3 or more people.

Book Now and I’ll see you in Barcelona in May

SharePoint Connections Amsterdam 2013 slide deck and Silly Facts demo source code

Last Tuesday and Wednesday the SharePoint Connections Amsterdam 2013 were held in Amsterdam, Netherlands. I did a session on Developing SharePoint 2013 Apps with Visual Studio 2012 and enjoyed it very much.

Besides my session I was on the Ask The Experts team for the DIWUG. Handed out the new edition of the DIWUG SharePoint eMagazine (download for free) and helped people with their questions. At the start of the conference is was quite, but along the way more and more people came up the Ask The Experts panel. Some interesting question, a big thanks for that!

In this article:

Demo 1: Silly Facts SharePoint-hosted App

The Silly Facts demo is about creating a list with silly facts, like the ones below. The list is provisioned in the App web using a Content Type and List Instance artifact.

Site Contents showing the Silly Facts app Default page as part of the app displaying the Facts list instance with generated silly facts 

Once the list is in place I added a App Part (Client Web Part) to the Host web which shows a random fact every time the page gets loaded.

Adding the App Part onto the page (simular like a web part) App Part showing random silly fact on page load

Next to generating silly facts via the JavaScript CSOM a Custom Action is hooked to an Announcement list in the Host web allowing users to easily add new facts to the Facts list.

Extending the context menu via the Custom Action 

Demo 2: Provider-hosted App retrieving data via CSOM and REST

The next demo is extending demo 1 and changing it to a Provider-Hosted app and adding logic for retrieving data with SharePoint via CSOM (Taxonomy) and REST (Search). Changing the SharePoint-Hosted app to a Provider-Hosted app is done in the AppManifest.xml. Here you can change the type and instantly it will ask to generate a Web Project for you.

Next step is adding the chrome which allows you to add a custom menu shown in the top right corner. You can add you own options which integrate with the chrome.

Changing the app type in the AppManifest.xml (in Visual Studio) Provider-Hosted app with chrome and menu customizations (top right corner) 

With everything in place we will retrieve Taxonomy data via the CSOM and perform search queries via the REST API. This is done via code-behind of the Default.aspx on the button click.

After clicking the button "Get Facts" it shows the silly facts with actual data from SharePoint The retrieved data is stored as a facts in the Facts list

Downloads

You can check the slide deck and source if you want. When you have question, please use the comments section below.

Source code is found on Codeplex: https://sillyfacts.codeplex.com/

SharePoint 2013 Client Browser: Now support for Taxonomy and User Profiles

It’s been around 2 months since the last release of the SharePoint 2o13 Client Browser but work has progressed! Today I updated the tool with two new features.

  • Taxonomy support by showing the hierarchy of Term Store, Groups, Term Sets and Terms.
  • Limited support for User Profiles by showing the User Profile of the current user with the related properties and peers.

Download the SharePoint 2013 Client Browser here!

Taxonomy

By using the Microsoft.SharePoint.Client.Taxonomy namespace it’s possible to get the complete hierarchy of the Term Store and even manipulate it.

SharePoint 2013 Client Browser showing the Taxonomy

User Profiles

Next to the Taxonomy SharePoint 2013 client object model is extended with the Microsoft.SharePoint.Client.UserProfiles namespace for interaction with the User Profiles. For now I only included the current user profile. Future releases will be extended with other properties and showing more user profiles of other users within the environment.

SharePoint 2013 Client Browser showing the User Profile of the current user

Slide deck and demos SharePoint Saturday 2013 Holland (#SPSNL13)

Last Saturday I presented at the SharePoint Saturday Holland 2013. It was a good vibe and the audience made it an interactive session. Below you can find the slide deck and parts of PowerShell scripts and source code which I used during my demos.

SharePoint Saturday Holland 2013

Developing hybrid SharePoint apps that run on-premise and in the cloud

With the new SharePoint App model running outside the SharePoint worker process it introduces new authentication models. As a developer you don’t want to build multiple versions of the same app implementing each authentication model separately. This session explains the differences between securing SharePoint apps with OAuth in Office 365 and S2S High Trust in on-premise deployments. You will learn how to build a single app that will run on-premise, online and hybrid SharePoint environments.

Demo: Configure the on-premise SharePoint with Trusted Security Token Issuer

To support high-trust (S2S) apps you need to configure the Trusted Security Token Issuer in your on-premise SharePoint farm. This script is used during the demo to configure the SharePoint farm.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ea 0 # Get the .cer file that you want to use with your app. $certificate = Get-PfxCertificate "C:\Apps\AppCertSP2013.cer" # Get the issuer ID of your app. All the letters in the issuer ID GUID must be lowercase. $issuerId = 'a58e2347-0ead-4ba0-b4b7-75120aa09e4e' # Get the current authentication realm for your SharePoint site $realm = Get-SPAuthenticationRealm -ServiceContext "http://vm-sp-01/sites/dev" # Get the issuer ID together with the realm value. $fullIssuerIdentifier = $issuerId + '@' + $realm # Create a trusted security token service. This fetches metadata from your app (for example, the certificate) and establishes trust with it, so that SharePoint 2013 can accept tokens that are issued by your app. New-SPTrustedSecurityTokenIssuer -Name $issuerId -Certificate $certificate -RegisteredIssuerName $fullIssuerIdentifier –IsTrustBroker

Demo: Build Hybrid app with a single codebase for on-premise and cloud

My last demo was building a Hybrid app that consists of a single codebase which runs both on-premise and in the cloud. The logic which determines if SharePoint is hosted in on-premise or in the cloud is below.

public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]); string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request); if (string.IsNullOrEmpty(contextTokenString)) { using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity)) { clientContext.Load(clientContext.Web, web => web.Title); clientContext.ExecuteQuery(); Response.Write(clientContext.Web.Title); } } else { using (var clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb.OriginalString, contextTokenString, Request.Url.Authority)) { clientContext.Load(clientContext.Web, web => web.Title); clientContext.ExecuteQuery(); Response.Write(clientContext.Web.Title); } } } }

DIWUG: Extending the My Site activity feed with external blog posts

Yesterday enjoyed another DIWUG user group meeting and presented the Extending the My Site activity feed with external blog posts. You can find the presentation here and I’ll make sure to create a Codeplex project soon. For now you can download the sources here.

DIWUG thanks again for arranging the event and Sogetti thanks for hosting.

Download PowerPointDownload

Hide “Fabulous 40” templates

The Fabulous 40 (a.k.a. Fab40 or Application Templates) are a set of 40 application templates for Windows SharePoint Services 3.0. These were installed on a lot of SharePoint 2007 environments.

When upgrading to SharePoint 2010 these templates become a challenge. The sites based on the Site Admin Templates (.STP) will be upgraded. After the upgrade these will likely work, but you can’t create any new sites based the STP templates, because SharePoint 2010 does not support STP files for site templates.

Sites which are based on the Server Admin Templates (.WSP) are more challenging because some Fab40 templates cannot be used for creating new sites in SharePoint 2010. To perform an upgrade you need to install the templates which are currently in use in the SharePoint 2007 environment.

To keep the new SharePoint 2010 environment as clean as possible you want to disable the creation of new sites based on the Fab40. You could choose to update the XML files on the file system (webtemp files in 14-hive), but the downside of this is you need to update all servers in the farm and when a new server is added this needs to be adjusted manually.

So I started looking into the order SharePoint reads the webtemp files when the application pool process (W3WP.exe) spins up on initial load. I used Process Monitor to research the file access in the “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\1033\XML\” folder. Based on the order shown in the screenshot below, it seems the “webtemp???.xml” files are loaded on alphabetical order. 

Process Monitor - Capturing the W3WP.exe process

Meaning if I would place a webtemp XML file which filename starts with “webtempaaa” it would load first and equally the filename “webtempzzz” would load at the end. Since underscores “_” are often used I wanted to check that particular filename as well. It seems a filename “webtemp_” is loaded at the end, instead of at the start (what I assumed).

The next question is: “Does SharePoint keep the settings which it reads in the first files or do these settings get overridden by settings in files loaded afterwards?”. The answer to this is it only stores the settings which it reads first. Meaning if I want to hide the templates I need to add a webtemp file with the name “webtempaaaHideFab40.xml”. Within the file I need to hide all the Fabulous 40 Server Admin Templates.

The XML file below shows the contents of the “webtempaaaHideFab40.xml” file:

<?xml version="1.0" encoding="utf-8" ?> <!-- Hides all Fabulous 40 templates, filename needs to begin with "webtempaaa..." to be loaded as the first one --> <Templates xmlns:ows="Microsoft SharePoint"> <Template Name="absence" ID="75811" SetupPath="SiteTemplates\absence" > <Configuration ID="0" Title="Absence and Vacation Schedule " Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="projmulti" ID="75819" SetupPath="SiteTemplates\projmulti" > <Configuration ID="0" Title="Budgeting and Tracking Multiple Projects" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="BT" ID="75801"> <Configuration ID="0" Title="Bug Database" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="callcenter" ID="75812" SetupPath="SiteTemplates\callcenter" > <Configuration ID="0" Title="Call Center" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="projchange" ID="75818" SetupPath="SiteTemplates\projchange" > <Configuration ID="0" Title="Change Request Management" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="comproc" ID="75813" SetupPath="SiteTemplates\compproc" > <Configuration ID="0" Title="Compliance Process Support Site" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="CM" ID="75802"> <Configuration ID="0" Title="Contacts Management" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="DR" ID="75803"> <Configuration ID="0" Title="Document Library and Review" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="eventplan" ID="75814" SetupPath="SiteTemplates\eventplan" > <Configuration ID="0" Title="Event Planning" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="exreports" ID="75815" SetupPath="SiteTemplates\exreport" > <Configuration ID="0" Title="Expense Reimbursement and Approval Site" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="helpdesk" ID="75816" SetupPath="SiteTemplates\helpdesk" > <Configuration ID="0" Title="Help Desk" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="IT" ID="75804"> <Configuration ID="0" Title="Inventory Tracking" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="itteam" ID="75817" SetupPath="SiteTemplates\itteam" > <Configuration ID="0" Title="IT Team Workspace" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="JRIM" ID="75805"> <Configuration ID="0" Title="Job Requisition and Interview Management" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="KB" ID="75806"> <Configuration ID="0" Title="Knowledge Base" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="LL" ID="75807"> <Configuration ID="0" Title="Lending Library" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="PATM" ID="75808"> <Configuration ID="0" Title="Physical Asset Tracking and Management" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="projsing" ID="75820" SetupPath="SiteTemplates\projsing" > <Configuration ID="0" Title="Project Tracking Workspace" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="RER" ID="75809"> <Configuration ID="0" Title="Room and Equipment Reservations" Hidden="True" DisplayCategory="Application Templates" /> </Template> <Template Name="ST" ID="75810"> <Configuration ID="0" Title="Sales Lead Pipeline" Hidden="True" DisplayCategory="Application Templates" /> </Template> </Templates>

Visio Services application development

Most people will know Visio as a client application for drawing diagrams like the Network Diagram, Floor Plan or Flowcharts. SharePoint 2010 introduced Visio as a server component with which diagrams drawn in Visio 2010 can easily be displayed within SharePoint and integrated into webpages. This article discusses the new Visio Services service application and possibilities for development with the Visio Services Mash-Up API.

Visio 2010 and Visio Services

The advanced diagramming tools of Microsoft Visio 2010 helps you to simplify complex (business) processes with dynamic, data-driven visuals and new ways to share on the Web. Visio 2010 visualizes processes by creating (process)diagrams, sharing these with colleagues and turn it into business intelligence. With the 2010 edition of Visio the product can be divided into a client and a server product. The client application is installed on the local computer of the information worker and provides powerful tooling for viewing and creating diagrams. Visio Services is a service application, which integrates with SharePoint Server 2010 and provides possibilities for viewing diagrams in a web browser.

Visio 2010 consists of three editions: Standard, Professional en Premium (http://office.microsoft.com/en-us/visio/visio-edition-comparison-FX101838162.aspx). The Standard edition has some basic features and focuses on View Only functionality. The Professional edition has most of the available features. It is likely this edition is most commonly used, because it supports a wide range of templates like floor plans for creating evacuation plans, pivot diagrams supporting hierarchical organizational structures and network diagrams for visualizing network topologies. The Premium edition has a specific set of features for Business Process Modeling Notation (BPMN), SharePoint workflow integration and Six Sigma templates.

Visio Services is part of SharePoint Server 2010 Enterprise edition. Visio Services is a service application that lets users share and view Visio Web drawings (*.vdw files). The service also enables data-connected Microsoft Visio 2010 Web drawings to be refreshed and updated from various data sources. Because diagrams are shown in the web browser there is no need for installing Visio 2010 on your local computer. Only “power users” will need Visio 2010 on their local computer for creating and changing diagrams. After the diagram is finished, the power users can easily share the drawing with the organization. Basic exploration and navigation of these rendered web drawings are supported within the Visio Web Access (VWA) web part. Page designers can configure the user interface and functionality of the web part. The diagram renders in full fidelity in the browser if the person viewing the diagram has Silverlight installed on their machine or as a PNG if not; Visio Services renders seamlessly anything you can draw in Visio. Take a look below to get a feel for the experience:

Supply Chain in browser

Figure 1: Visio drawing rendered in web browser by Visio Web Access web part

Integrating Visio diagrams into SharePoint Applications

Visio Services enables you to embed Visio Web Diagrams into SharePoint applications. There are no limitations whether the diagram is static or dynamic. Depending on your skill level there are three ways of doing so (see Table 1). No matter your skill level, with very little effort you can add visualization to your dashboards and with a bit more page authoring or some coding you can add rich interactivity between Visio Services and other components on the page.

Integration method

Scenario enabled

Skill set required

The Visio Web Access web part

You can embed Visio diagrams into SharePoint pages.

You should know how to create a web part page in SharePoint.

Web Part Connections

You can enable limited interactivity between the Visio Web Access web part and another web part on the page, without code. A typical example of this type of interactivity is to trigger one web part to show extra relevant information about a particular shape, when it’s clicked in the Visio web part.

You should know how to create a web part page in SharePoint as well as how to set-up web part Connections.

The Visio Services Mash-up API

You can enable rich interactivity on your web part page by manipulating the different Visio web diagram objects programmatically. A typical example of this type of interactivity is to show custom visual overlays when the person viewing the diagram hovers over a particular shape.

You should know how to code JavaScript and/or ASPX pages.

Table 1: Integration Visio and SharePoint

The Visio Services Mash-Up API

The Visio Services Mash-Up API is the most advance integration method of all and requires development skills. It enables developers to access and manipulate the Visio web drawing, its pages and shapes. Some key scenarios are:

  • Interacting with web page elements that don’t expose web part connections.
  • Creating visual markup on the Visio drawing canvas.
  • Writing custom handlers for mouse events within the drawing.
  • Exposing diagram data, such as shape names and shape data, to your solution.
  • Combining data from inside and outside a diagram to build dynamic composite mash-ups.

The Mash-Up API consists of four major classes, which reside in the Microsoft SharePoint Server 2010 ECMAScript (JavaScript, JScript) Vwa namespace (http://msdn.microsoft.com/en-us/library/ff394600.aspx). The Vwa.VwaControl class represents the Visio Web Access (VWA) web part on the page. This is the starting point for development. The VWA web part contains a link to the Visio Web Drawing and shows the drawing on the web page. Like many JavaScript APIs, the Visio Services JavaScript API is event-based. The VwaControl exposes a number of events, which a developer can use to write event handlers. Important to note is the event handlers can only be accessed from within the onDiagramComplete event. So typically when the onApplicationLoad event fires, a reference to the VwaControl can be instantiated. This is where you want to set-up the handlers for the onDiagramComplete event and other various (mouse) events. Only then, when the onDiagramComplete event fires references to the complete object model are available.

Most of the business logic starts from the onDiagramComplete event where the (active) page is accessed. The page is represented by the Vwa.Page class which contains a collection of Shapes (Vwa.ShapeCollection class). You can either retrieve the current selected shape or iterate the shapes collection to get a particular shape (Vwa.Shape class).

Microsoft floor plan

Microsoft Netherlands invites customer and partners to visit their building located in Schiphol on a daily basis. The building is split up into a public community area (first floor) and a private area for employees only. The community area holds room for 15 conference rooms, with different capacity and facilities like a beamer and a Roundtable.

Microsoft wanted to improve the process for booking a room, by visualizing the community area and support the room selection process by highlighting rooms, which comply with given selection criteria. Selecting a room is based on availability, capacity and beamer and/or Roundtable availability.

The basics for starting development is creating the Visio web diagram. The community area diagram is created by importing a CAD drawing. This resulted in a Visio diagram showing the community area. By importing the CAD drawing the diagram was overloaded with a huge number of shapes. Every wall resulted in a one or more shapes. When joining shapes together shapes representing one room are created. This is a very important step because in Visio it is all about shapes!

In Visio it is all about shapes!

A single shape contains shape data. The Shape Data Window, showing all shape data, is accessed via the Data tab in the Visio ribbon. Figure 2 is showing the selected shape “Het Kantoor” and its shape data on the right in the Shape Data Window.

The next step in creating our floor plan application is adding data to the shapes. Microsoft provided an Excel sheet with information about capacity and facilities. This information is easily imported into the drawing and bound to the shapes. Visio supports importing data from different sources like Excel, Access, SharePoint, SQL and other sources by clicking the Link Data to Shapes button in the Data tab. The imported data has become a part of the diagram and is stored within the diagram. It is even supported to update the data in the Excel sheet and refresh the corresponding data within the Visio drawing. After the import the External Data window is shown. By dragging a row onto a shape the shape is linked with external data. In Figure 2 the row “Het Atelier” is dragged to the corresponding shape for linking the data to the shape. We will link all rows to the corresponding shapes.

ShapeDataDataLinking

Figure 2: Floor plan zoomed in on "Het Kantoor" conference room

At this stage the Visio diagram is ready. It is saved to a SharePoint site as a Visio Web Diagram (.vwd) file. This is a new Visio file format to support a data-refreshable drawing for use with Visio Services. With the SharePoint site up and running and our Visio diagram saved to a document library, a web part page is needed to display the diagram. A basic web part page with “Header, Right Column, Body” layout is created. Two web parts are added. The Visio Web Access web part is added in the “Body” web part zone and a Content Editor web part is added to the “Right” zone (Figure 3).

WebPartPageWithVWA

Figure 3: Web part page with Visio Web Access web part added to Body web part zone

The VWA web part needs to be configured by selecting the Visio diagram, which is stored in the document library. All other properties of the web part are unchecked in this case, because they will be set via JavaScript later in this article.

VisioWebPartProperties

Figure 4: Visio Web Access web part properties

The Content Editor web part will be pointed to a JavaScript file containing the HTML markup for the panel on the right and all JavaScript business logic. The panel is used by the end user for interaction with the diagram (Figure 5). It shows room information when hovering the different conference rooms (shapemouseenter and shapemouseleave events). Users can use the Filter Options section to highlight in red the matching conference rooms. The Meeting Rooms section will list all available conference rooms by iterating the diagram and building a bulleted list. When clicking an item in the list the conference room is highlighted in light blue.

FloorPlan

Figure 5: Screenshot of Floor Plan Application

Change the Visio Services service application configuration setting Cache Age to 0 minutes. This will reload the Visio drawing on a page refresh. Don’t use this setting in Production environment!

Getting started with the mash-up API

Finally we can start working on our JavaScript skills. First step is to hook up the Application event handlers and get a reference to the VwaControl object (Listing 1). The VwaControl object can be retrieved via the web part instance. Open the SharePoint web part page in source mode (in IE, right click and “View Source”) and search for “class=’VisioWebAccess’”,then back track to the immediate parent <div> tag and look for an attribute of the form id="WebPartWPQ?". Use this ID for retrieving the VwaControl.

// hook up Application event handlers var app = Sys.Application; app.add_load(onApplicationLoad); app.add_unload(onApplicationUnload); // hold an instance of the Visio VWA control var vwaControl; //---------------------------------------------------------- // Create a VwaControl Object and add handlers. //---------------------------------------------------------- function onApplicationLoad() { // this is the name of the visio web part instance on the web part page vwaControl = new Vwa.VwaControl("WebPartWPQ3"); vwaControl.addHandler("diagramcomplete", onDiagramComplete); vwaControl.addHandler("shapeselectionchanged", shapeSelectionChangedHandler); vwaControl.addHandler("shapemouseenter", onShapeMouseEnter); vwaControl.addHandler("shapemouseleave", onShapeMouseLeave); }

Listing 1: Hook up the Application event handlers and reference VwaControl object

After setting up the basics, it’s coding the event handlers. The most important event is the onDiagramComplete event (Listing 2). This is where the active page is retrieved and initial zoom level is set. To make sure the end user does not click the buttons before Visio Services is ready with loading the diagram, the buttons are enabled here in this event.

//---------------------------------------------------------- // Visio page events //---------------------------------------------------------- function onDiagramComplete() { var vwaPage = vwaControl.getActivePage(); vwaPage.setZoom(-1); // force the initial zoom level // Enable filter buttons document.getElementById('btClear').disabled = false; document.getElementById('btFilter').disabled = false; // Get all meeting rooms based on drawing. GetRooms(); // Select shape when querystring has parameter 'room' var roomName = getQuerystring('room', ''); if (!roomName.isNullOrEmpty()) setSelectedShapeByLabelAndName(labelRoomName, roomName); } shapeSelectionChangedHandler = function (source, args) { GetShapeInformation(args); } onShapeMouseEnter = function (source, args) { GetShapeInformation(args); } onShapeMouseLeave = function (source, args) { // Could add logic for mouse leave event }

Listing 2: onDiagramComplete event

The setSelectedShapeByLabelAndName and GetShapeInformation methods are not described in this article. Both are based on the same principles as described in the following paragraph.

Iterate shapes and retrieving shape data

As mentioned earlier, all shapes on the diagram are iterated to get all conference rooms and list those in the Meeting Rooms section. This is initiated by calling the GetRooms() method.

The room name is displayed in the bulleted list on the web page, this is stored in the shape data collection as shown in Figure 2. The shape data is a label/value pair collection which is accessed by the nextShape.getShapeData(); statement. To get the Shape object, the ShapeCollection needs to be iterated. This is an important approach to retrieve shape data in the Visio Mash-Up API. This is shown in Listing 3.

//---------------------------------------------------------- // Get all rooms from the diagram and provision in DIV-element //---------------------------------------------------------- var labelRoomName = "naam"; function GetRooms() { // Get visio objects var vwaPage = vwaControl.getActivePage(); var vwaShapes = vwaPage.getShapes(); var vwaShapeCount = vwaShapes.getCount(); // Search shape based on label and value var strHtml = "<ul class=\"visioRooms\">"; for (var nextShapeIndex = 0; nextShapeIndex < vwaShapeCount; nextShapeIndex++) { var nextShape = vwaShapes.getItemAtIndex(nextShapeIndex); if (nextShape != null) { var data = nextShape.getShapeData(); var strRoomName = ""; for (var j = 0; j < data.length; j++) { if (data[j].label == labelRoomName) { strRoomName = data[j].value; continue; } } if (!strRoomName.isNullOrEmpty()) strHtml += "<li><a href=\"javascript:setSelectedShapeById('" + nextShape.getId() + "');\">" + strRoomName + "</a></li>"; } } strHtml += "</ul>"; } //---------------------------------------------------------- // Sets the selected shape by shape ID //---------------------------------------------------------- function setSelectedShapeById(shapeId) { // Get page and set shape var vwaPage = vwaControl.getActivePage(); vwaPage.setSelectedShape(shapeId); }

Listing 3: Iterate all shapes

Highlight shapes

When a user clicks the “Highlight”-button all shapes which comply with given selection criteria will be highlighted in red. This is achieved with the out-of-the-box method Shape.addHighLight object. An example is shown in Listing 4 which is a fragment of the custom Highlight method.

var selectShape = true; if (selectShape) { nextShape.addHighlight(4, 'red');

Listing 4: Highlight shape

Conclusion

In this article we have looked at developing Visio applications running on top of Visio Services. The article provides background information about Visio 2010 and the new SharePoint 2010 Visio Services service application. Visio Services supports displaying a Visio Web Drawing (.vwd file extension) in the Visio Web Access web part. A developer can easily interact with the Visio drawing by using the Visio Services Mash-Up API. This is demonstrated with the Microsoft floor plan example. Hopefully this has given you an understanding of the Visio development basics and an example approach to creating your own Visio mash-up application.