35
Hands-On Lab Solution Development with Excel Services Lab version: 1.0.0 Last updated: 6/1/2022

Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

Hands-On LabSolution Development with Excel Services

Lab version: 1.0.0

Last updated: 5/21/2023

Page 2: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

CONTENTS

OVERVIEW................................................................................................................................................. 3

EXERCISE 1: BASIC EXCEL SERVICES ECMASCRIPT OBJECT MODEL USAGE..............................5Task 1 – Reviewing Starting Materials and Setup Test Page................................................................5

Task 2 – Adding Initialization Code to the TCO JavaScript File.............................................................9

Task 3 – Adding Navigation Functionality............................................................................................9

Exercise 1 Verification.......................................................................................................................12

EXERCISE 2: ADVANCED EXCEL SERVICES ECMASCRIPT OBJECT MODEL USAGE...................13Task 1 – Providing a Reset Feature....................................................................................................14

Task 2 – Adding a Machine Selection Feature...................................................................................18

Exercise 2 Verification.......................................................................................................................22

EXERCISE 3: INTERACTING WITH THE REST API AND EXCEL WEB SERVICES.............................22Task 1 – Implementing a File Save Feature........................................................................................23

Task 2 – Enhancing the UI with a Chart.............................................................................................25

Exercise 3 Verification.......................................................................................................................27

SUMMARY................................................................................................................................................ 29

Page 3: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

Overview

Excel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to create server-based Excel solutions either on-premise or in the cloud with Office 365. This Hands-On Lab will explore some of the common tasks that developers perform while working with Excel Services.

Objectives

The objective of this Hands-On Lab is to provide you with a foundation for developing solutions that utilize or interact with Excel Services. In particular, you will

Learn how to use the Excel Services ECMAScript Object Model

Understand how to access resources within an Excel workbook using the Excel Services REST API

Learn the technique for calling into the Excel Web services using ECMA Script

System Requirements

Note: To work this lab, there is an assumption that you have a SharePoint environment running Excel Services in place. This lab was designed to run on the “2010 Information Worker Demonstration and Evaluation Virtual Machine (RTM).” Here is the URL at the time this document was created, but it’s best to search for the above name on Bing to make sure you have the most current version. http://www.microsoft.com/downloads/en/details.aspx?FamilyID=751fa0d1-356c-4002-9c60-d539896c66ce&displaylang=en. For instructions on how to setup this environment, see this video, http://channel9.msdn.com/Shows/SharePointSideshow/Setting-Up-a-SharePoint-Developer-Virtual-Machine. Or to setup SharePoint on a test Windows 7 machine, see this video, http://channel9.msdn.com/Shows/SharePointSideshow/Building-a-SharePoint-Development-Machine-Using-the-Easy-Setup-Script.

The steps in this Hands-On Lab require the following:

SharePoint 2010

Excel 2010

Visual Studio 2010

Page 4: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

Setup

This Hands-On Lab assumes that the Hands-On Lab files are located in a folder at C:\Student\ExcelServices. To get these files there, perform the following steps

1. Open Windows Explorer

2. Right-click on the Local Disk (C:) item and choose NewFolder

3. Name the new folder Student

4. Right-click on the Student folder and choose NewFolder

5. Name the new folder ExcelServices

6. Open up the zip file named ExcelServices.zip (found in the %Office2010DeveloperTrainingKitPath%\Labs\SolutionDevelopmentExcelServices\Source\Starter folder for this lab)

7. Drag the items in the zip folder into the ExcelServices folder

8. Open a browser and navigate to the SharePoint site http://intranet.contoso.com/Shared%20Documents/

9. Click Add document.

10. Browse to C:\Student\ExcelServices\ and select the file named Contoso TCO.xlsx

11. Click Open

12. Click OK to begin uploading the document.

Exercises

This Hands-On Lab comprises the following exercises:

1. Basic Excel Services ECMAScript Object Model Usage

2. Advanced Excel Services ECMAScript Object Model Usage

3. Interacting with the REST API and Excel Web Services

Estimated time to complete this lab: 60 minutes.

Starting Materials

This Hands-On Lab includes the following starting materials.

ContosoTCO.xlsx – This is an Excel workbook which serves as the focus of the exercise.

ContosoTCO.js – A JavaScript file containing some base functionality that you will expand upon.

Page 5: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

Exercise 1: Basic Excel Services ECMAScript Object Model Usage

The programmability story around Excel Services increased dramatically in SharePoint Server 2010. In addition to the expanded capabilities of the Excel Web Services, there is a REST API for accessing resources in Excel workbooks using a URL and an ECMAScript or JavaScript object model (JSOM). You can use all three options within a single solution to create sophisticated web-based applications. In Exercise 1, you will learn the basics of using the Excel Services JavaScript Object Model (JSOM).

Note: The Excel Services ECMAScript object model is available in Office 365. All of the techniques demonstrated in exercise 1 are cloud friendly.

Task 1 – Reviewing Starting Materials and Setup Test Page

In order to provide some structure and help clarify future tasks, this Hands-On Lab starts with a JavaScript file that contains minimal functionality along with place holders for code you need to complete. In order to test your work, you need to setup a web part page in SharePoint that includes two web parts: an Excel Web Access web part that points to a TCO model, and a Content Editor Web part that refers to the TCO JavaScript file.

1. Review the TCO Model

a. TCO stands for Total Cost of Ownership. Companies often use TCO models in industries that sell expensive machinery where the acquisition cost is just a fraction of the overall cost of operating a piece of machinery. This TCO model is an example of one you might find in the Farm Machinery industry.

b. In Internet Explorer, navigate to http://intranet.contoso.com/Shared%20Documents/

c. Click on the Contoso TCO to open the TCO workbook in the browser.

Page 6: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

Figure 1TCO Calculator

d. Note the notification about Unsupported Features at the top of the window. Many non-trivial workbooks will contain items that Excel Services does not fully support. In particular, the TCO workbook contains a few Shape objects that Excel Services does not render.

e. Click on the Start, Machine Inputs, TCO Result, and Data worksheets and briefly review the contents. The worksheets not called out are not relevant to this lab.

i. The Start worksheet contains inputs specific to a customer.

ii. The Machine Inputs worksheet contains the inputs associated with the machines that you want the model to compare.

iii. The TCO Result worksheet provides concise information regarding the results of the model calculations.

Page 7: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

iv. The Data worksheet stores information related to machines. The information on this worksheet serves as the default values supplied to the Machine Inputs worksheet.

2. Review the TCO JavaScript file

a. Open Visual Studio 2010.

b. Open the file named TCOModel START.js

c. Create a working copy named TCO.js

i. FileSave As…

ii. Save the file as C:\Student\ExcelServices \TCO.js

d. Near the top of the file, observe the numerous <div /> elements. You will use these items to provide a basic UI within a Content Editor Web part in SharePoint.

e. Within the script section, notice the comments beginning with the text “TO DO”. You will flush these sections out throughout the lab.

3. Create the TCO Reporting web part page

a. In Internet Explorer, navigate to http://intranet.contoso.com/SiteAssets/

b. Click Add document

c. Upload C:\Student\ExcelServices \TCO.js.

d. Select Site ActionsMore Options…

e. Choose Web Part Page and click Create

i. Name: TCO Calculator

ii. Layout: Header, Left Column, Body

iii. Save Location: Site Pages

f. In the Body container, click Add a Web Part

i. In the Business Data category, select Excel Web Access and click Add

ii. Within the Excel Web Access part, click the link labeled Click here to open the tool pane.

iii. Change the following properties:

a. Workbook: http://intranet.contoso.com/Shared Documents/Contoso TCO.xlsx

b. Type of Toolbar: None

c. Height: 650

d. Chrome Type: None

Page 8: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

e. Click OK to save changes and close tool pane

g. In the Left Column container, click Add a Web Part

i. In the Media and Content category, select Content Editor and click Add

ii. In the Content Editor part, click on the drop-down button next to the label Content Editor and choose Edit Web Part

iii. Change the following properties:

a. Content Link: http://intranet.contoso.com/SiteAssets/TCO.js

b. Title: Contoso TCO Calculator

c. Width: 300 Pixels

d. Chrome Type: Title Only

e. Click OK to save changes and close tool pane

h. Click Stop Editing in the ribbon to save your changes and exit page edit mode. At this point, you have a framework for testing your changes as you proceed through the lab. As you make changes to the TCO.js file, you can test them by saving the TOC.js file to the SiteAssets library and then refreshing the TCO Calculator web part page.

Figure 2TCO Calculator

Page 9: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

4. Save a blank Excel document to C:\Student\ExcelJSOM\Started and name the document EwaTest.xlsx.

Task 2 – Adding Initialization Code to the TCO JavaScript File

The first step in any script that uses the Excel Services JSOM is to add code that obtains a reference to the EwaControl, the primary object of the JSOM, and then use the EwaControl to obtain a reference to the Excel Web Access web part that you want to add functionality too.

1. If it’s not already open, open the TCO.js file in Visual Studio 2010

2. Within the <script /> node, locate the initial group of comments beginning with the comment // TO DO: Add standard Excel JSOM initialization.

3. Add the following code underneath the comment // GetEwa(). This code is responsible for associating the script with the Excel Services JSOM and then obtaining a reference to the Excel Web Access web part on the same page that is displaying the Contoso TCO workbook.

JavaScript

// SCRIPT LEVEL VARIABLESvar xlWebPart;

// Set the page event handlers for onload and unload.if (window.attachEvent) { window.attachEvent("onload", Page_Load); }else { // For some browsers window.attachEvent does not exist. window.addEventListener("DOMContentLoaded", Page_Load, false); }

// Load the page. function Page_Load() { Ewa.EwaControl.add_applicationReady(GetEwa);}

// Get handle to EWA instance, set event handlers and initialize contentfunction GetEwa() { xlWebPart = Ewa.EwaControl.getInstances().getItem(0); // TO DO: xlWebPart.add_activeSelectionChanged(onSelectionChange); // TO IMPLEMENT: getChartImage("get"); // TO IMPLEMENT: fillMachineDropdowns("get"); // TO IMPLEMENT: createHyperLinks();}

Page 10: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

Task 3 – Adding Navigation Functionality

One of the easiest features to add using the Excel Services JSOM is workbook navigation. Workbook navigation provides users with a simple way to navigate complex workbooks. In the Excel client, you can use hyperlinks, embedded controls, or shapes associated with macros to provide workbook navigation. In the browser, there are two options: hyperlinks and cells formatted to look like buttons that are associated with a selection event handler.

1. Locate the group of comments beginning with the comment // TO DO: Add navigation functionality

2. Add the following code underneath the comment // createHyperLinks(). This code uses the Excel Services JSOM to loop through the visible worksheets in the Excel Web Access web part, creating a hyperlink for each sheet, and adding it to the ‘hyperlinks’ <div /> element.

JavaScript

// Gets the sheets associated with the workbook (visible sheets only) and creates a // hyperlink for navigation purposes.function createHyperLinks(){ var sheets = xlWebPart.getActiveWorkbook().getSheets(); document.getElementById('hyperlinks').innerHTML = '<h3 style="color:#018FC3;margin-bottom:2px;' + 'padding-bottom:2px;">Model Navigation</h3>'; for(var i = 0; i < sheets.getCount(); i++) { sheet = sheets.getItem(i);

document.getElementById('hyperlinks').innerHTML += '<a style="color:#018FC3;" href=\'javascript:hyperlinksheet_onclick("' + sheet.getName() + '")\'>' + sheet.getName() + '</a><br />'; } document.getElementById('hyperlinks').innerHTML += '<h3 style="color:#018FC3;margin-bottom:2px;padding-bottom:2px;">Other</h3>'; document.getElementById('hyperlinks').innerHTML += '<div id="machinehl"><a style="color:#018FC3;" ' + 'href=\'javascript:hyperlink_onclick("machinedd")\'>' + 'Show Machine Selection</a></div>'; document.getElementById('hyperlinks').innerHTML += '<a style="color:#018FC3;" ' +

Page 11: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

'href=\'javascript:hyperlink_onclick("savediv")\'>' + 'Save Workbook Copy</a>'; document.getElementById('hyperlinks').innerHTML += '<br /><a style="color:#018FC3;" ' + 'href=\'javascript:hyperlink_onclick("refreshChart")\'>Refresh Chart</a>';

//Set default file name copy value of file name input box var workbookPath = xlWebPart.getActiveWorkbook().getWorkbookPath(); var workbookName = workbookPath.substring(workbookPath.lastIndexOf("/") + 1, workbookPath.lastIndexOf("."));

document.getElementById('fileName').value = workbookName + '-Copy';}Add the following code underneath the comment // hyperlinksheet_onclick(). The hyperlinksheet_onclick function is the event handler called when you click on one of the sheet hyperlinks within the ‘hyperlinks’ <div /> element. The hyperlink_onclick function is the event handler for click on the hyperlinks that do not refer to worksheets.//Event handler for hyperlinks related to sheet navigationfunction hyperlinksheet_onclick(sheetName){ var cell = 'A1'; xlWebPart.getActiveWorkbook().getRangeA1Async("\'" + sheetName + "\'!" + cell, getRangeComplete);}

// Event handler for hyperlink unrelated to workbook sheet navigation// Handles displaying/hiding the machine selection drop downs, refreshing the chart, // and displaying the save contentfunction hyperlink_onclick(name){ if(name == 'savediv') { document.getElementById('savediv').style.display = 'block'; document.getElementById('saveresult').innerHTML = ''; } else if(name == 'machinedd') { if(document.getElementById('machinedd').style.display == 'block') {

Page 12: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

document.getElementById('machinehl').innerHTML = '<a style="color:#018FC3;" ' + 'href=\'javascript:hyperlink_onclick("machinedd")\'' + '>Show Machine Selection</a>';

document.getElementById('machinedd').style.display = 'none'; } else { document.getElementById('machinehl').innerHTML = '<a style="color:#018FC3;" ' + 'href=\'javascript:hyperlink_onclick("machinedd")\'' + '>Hide Machine Selection</a>'; document.getElementById('machinedd').style.display = 'block'; } } else if(name == 'refreshChart') { getChartImage("get"); }}

3. Add the following code underneath the comment // getRangeComplete(). Calls to most functions within the JSOM are asynchronous. This function is the callback that the JSOM calls after it returns with the range specified in the getRangeA1Async method call (called in hyperlinksheet_onclick in Step 3). The purpose of this function is to activate the desired range thereby forcing the Excel Web Access web part to navigate to the desired worksheet.

JavaScript

// Callback function that sets the focus of the rangefunction getRangeComplete(asyncResult){ var range = asyncResult.getReturnValue(); range.activateAsync();}

4. Locate the GetEwa() function you added in Task 2, Step 3 and modify the line // TO IMPLEMENT: createHyperLinks() as shown below.

JavaScript

createHyperLinks();

Page 13: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

Exercise 1 Verification

To check your work thus far, perform the following steps.

1. In Visual Studio 2010, press CTRL + S to save your work.

2. Open Internet Explorer and navigate to http://intranet.contoso.com/SiteAssets/

3. Click Add document

4. Click Browse and select the TCO.js file in C:\Student\Excel Services

5. Click Open

6. Click OK to upload the document (make sure Overwrite existing files is checked)

7. Navigate to http://intranet.contoso.com/SitePages/TCO Model.aspx

Figure 3TCO Calculator

8. Click on the various links under Model Navigation and verify that the Excel Web Access web part displays the correct worksheet. Note that the links under the section labeled “Other” will not work until you add the necessary functionality later in this lab.

Page 14: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

Exercise 2: Advanced Excel Services ECMAScript Object Model Usage

In the last exercise you learned how to provide basic workbook navigation using the JSOM. A slightly more advanced use of the JSOM is to manipulate the data within a workbook. Additionally, you can use the JSOM to extract data out of a workbook for other uses such as populating controls in other web parts on a web page. In Exercise two, you’ll utilize both of these techniques in order to provide “Reset” functionality and to provide a way to change which machines are selected in the model.

Note: All of the techniques demonstrated in exercise 2 are cloud friendly.

Task 1 – Providing a Reset Feature

Ideally, the TCO model would allow you to select a machine and populate the model variables with the default values associated with the machine. After you interact with the variables to perform an ad-hoc “what-if” analysis, you may want to reset the variables to the defaults associated with the machine. For example, on the Machine Inputs worksheet, you could change things like the selling price or the residual value and see the effect on the total cost of ownership. When you click reset, these values revert to their original settings. In this task you will implement this “Reset” functionality.

1. If it’s not already open, open the TCO.js file in Visual Studio 2010

2. Locate the GetEwa() function you added in Exercise 1, Task 2, Step 3 and modify the line // TO DO: xlWebPart.add_activeSelectionChanged(onSelectionChange); as shown below.

JavaScript

xlWebPart.add_activeSelectionChanged(onSelectionChange);

3. Within the <script /> node, locate the initial group of comments beginning with the comment // TO DO: Add functionality for resetting workbook.

4. Add the following code underneath the comment // onSelectionChange(). This code is an event handler the Excel Web Access part triggers as you change the selection. If you look on the Machine Inputs worksheet, you see the text “reset this item” above each machine. This event handler looks to see if the selected cell is one of those cells and, if it is, calls the resetModel function that you’ll implement in the next step.

JavaScript

// Event handler for cell selection changes. function onSelectionChange(rangeArgs) {

Page 15: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

selectedAddress = rangeArgs.getRange().getAddressA1(); if(selectedAddress == "'Machine Inputs'!E6") resetModel('1'); else if(selectedAddress == "'Machine Inputs'!F6") resetModel('2'); else if(selectedAddress == "'Machine Inputs'!G6") resetModel('3');}

5. Add the following code underneath the comment // resetModel(). The primary purpose of this function is to initiate the process of retrieving the data associated with model indicated by the modelIndex argument. On the Data worksheet, there is a named range for each machine (Machine1, Machine2, and Machine3). This function uses the JSOM method getRangeA1Async to initiate the process of retrieving this range. The JSOM will call the method specified (getMachineInputRangeComplete in this example) when it returns. The final argument supplied to getRangeA1Async is a user context argument. You can add your own data in this argument and the JSOM will pass it back to your callback function so that your callback function is aware of the context in which the JSOM calls it. The second part of this function retrieves the list of manufacturers in the model.

JavaScript

// Reset values on Machine Inputs page to default settingsfunction resetModel(modelIndex) { xlWebPart.getActiveWorkbook().getRangeA1Async( "'Data'!Machine"+modelIndex, getMachineInputRangeComplete, 'ResetMachine' + modelIndex); var rows = new Array('','6','7','8'); var rowIndex = rows[parseInt(modelIndex)]; xlWebPart.getActiveWorkbook().getRangeA1Async( "'Data'!AA" + rowIndex, getMachineInputRangeComplete, 'MachineManu' + modelIndex); }

6. Add the following code underneath the comment // getMachineValuesComplete(). After retrieving the machine input range, the JSOM calls the callback named getMachineInputRangeComplete that you specified in the previous step. Although you have the desired range at this point, you do not have the values. In order to get the values, you have to call the getValuesAsync() method as demonstrated in

Page 16: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

getMachineInputRangeComplete. When you call this method, you specify whether you want the formatted value or the raw value, the name of callback, and any user context data to include. In this example, getMachineValuesComplete() is the specified callback. Depending on the user context, this function calls one of several other methods to do the actual work with the values that the JSOM returned.

JavaScript

// Call back function used when values need to be retrieved from the // active workbookfunction getMachineInputRangeComplete(asyncResult) { var format = null; asyncResult.getReturnValue().getValuesAsync( format, getMachineValuesComplete, asyncResult.getUserContext());}

// Call back function for values being retrieved from the workbookfunction getMachineValuesComplete(asyncResult){ var values = asyncResult.getReturnValue(); if (values.length > 0) { if(asyncResult.getUserContext() == 'AvailableMachines') { fillMachineDropdowns("set",values); } else if(asyncResult.getUserContext() == 'MachineTotalCosts') { getChartImage("set",values); } else if(asyncResult.getUserContext() == 'SelectedMachines') { fillMachineDropdowns(" ",values); } else if(asyncResult.getUserContext().substr(0,12) == 'ResetMachine') { //reset models var resetIndex = parseInt( asyncResult.getUserContext().substr(12,1)); var columnNames = new Array("","E","F","G"); var column = columnNames[resetIndex];

Page 17: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

xlWebPart.getActiveWorkbook().getRangeA1Async( "'Machine Inputs'!"+column+"12:"+column+"31", getInputsNamedRangeComplete, values); } else if(asyncResult.getUserContext().substr(0,11) == 'MachineManu') { var resetIndex = parseInt( asyncResult.getUserContext().substr(11,1)); xlWebPart.getActiveWorkbook().getRangeA1Async( "'Machine Inputs'!M"+resetIndex+"Manu", getInputsMachineName, values); } }}

7. Add the following code underneath the comment // getInputsMachineName(). The two functions shown in this block of code are responsible for taking the values obtained in the previous calls to getValuesAsynch() and setting the values of the desired ranges on the Machine Inputs worksheet. This whole process transfers data from the Data worksheet to the Machine Inputs worksheet. You could achieve a similar result using lookup formulas. However, the limitation of using lookup formulas is that as soon as you enter a new value in the cell to perform ad-hoc “what if” analysis, you overwrite the formula with a literal value. Consequently, there is not a way to “Reset” back to the original value.

JavaScript

// Call back function for setting the manufacturer names in // the Machine Inputs sheetfunction getInputsMachineName(asyncResult){ var range = asyncResult.getReturnValue(); var values = asyncResult.getUserContext(); var valueArray = new Array(1); valueArray[0] = new Array(1); valueArray[0][0] = values[0][0]; range.setValuesAsync(valueArray);} // Call back function for setting the default values for each// machine in the Machine Inputs sheet

Page 18: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

function getInputsNamedRangeComplete(asyncResult){ var range = asyncResult.getReturnValue(); var values = asyncResult.getUserContext(); var valueArray = new Array(20); for(var i = 0; i < 20; i++) valueArray[i] = new Array(1); valueArray[0][0] = values[0][2]; valueArray[1][0] = values[0][3]; valueArray[2][0] = values[0][10]; valueArray[3][0] = values[0][15]; valueArray[4][0] = values[0][16]; valueArray[7][0] = values[0][4]; valueArray[8][0] = values[0][5]; valueArray[9][0] = values[0][6]; valueArray[12][0] = values[0][7]; valueArray[13][0] = values[0][8]; valueArray[16][0] = values[0][11] * 100; valueArray[17][0] = values[0][12] * 100; valueArray[18][0] = values[0][13] * 100; valueArray[19][0] = values[0][14] * 100; range.setValuesAsync(valueArray); // Now that the values have been set, update the chart to // reflect the new information // TO DO: getChartImage("get"); }

Task 2 – Adding a Machine Selection Feature

In order to be truly useful, a TCO model would allow you to select from a wide range of competing machines rather than be hard-coded to the same three machines. On the Excel client, you might use VBA or VSTO to provide the user interface and related functionality to implement this feature. In the browser, you can recreate this functionality using standard HTML controls and JavaScript along with the Excel Services JSOM.

1. One of the <div /> nodes at the top of the TCO.js file contains three drop-down lists. One of the first things to do is add code to populate each of these drop-down lists with the list of machines available in the model. Locate the GetEwa() function you added in Exercise 1, Task 2, Step 3 and modify the line // TO IMPLEMENT: fillMachineDropdowns(“get”) as shown below. You will implement this function shortly.

Page 19: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

JavaScript

fillMachineDropdowns("get");

2. Add the following code underneath the comment // dropdown_onchange(). This is the event handler specified in the drop-down controls for the change event. Much of the process for selecting a machine follows the pattern for resetting a machine. That is, locate the data on the Data worksheet, obtain the values, and then transfer the values to the appropriate cells on the Machine Inputs worksheet. The process begins by getting the range on the Data worksheet associated with the machine selected in the drop-down.

JavaScript

//Event handler for changes with the machine selection drop downfunction dropdown_onchange(event){ if(event == null || event.selectedIndex < 0) return; var machineIndex = event.options[event.selectedIndex].value; // first item in the list. not an actual machine if(machineIndex == "null") return; var machineName = event.options[event.selectedIndex].text; xlWebPart.getActiveWorkbook().getRangeA1Async( machineIndex, getMachineInputRange, machineName);}

3. Add the following code underneath the comment // setMachineInput(). The dropdown_onchange event handler in Step 2 calls getRangeA1Asynch. When getRangeA1Asynch returns, it calls getMachineInputRange. getMachineInputRange observes the value associated with the range and sets a value on the Data worksheet that indicates what the current machine is. The Data worksheet uses VLOOKUP functions to lookup the correct information from the range of data on the worksheet containing all of the available machines. In order to set values on a worksheet, the JSOM provides a function named setValuesAsync. setValuesAsync accepts three arguments: an array containing the values to set, the name of a callback function, and a user context argument. In the code below, the function setMachineInput is the callback function specified in the call to setValuesAsync. setMachineInput determines which machine was changed and then leverages the

Page 20: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

functionality provided by the “Reset” functionality from the prior task to update the model with the correct information.

JavaScript

// Call back function for changing the model key in the Data sheet // to reflect changes within the machine selection drop downfunction getMachineInputRange(asyncResult){ var range = asyncResult.getReturnValue(); var machineName = asyncResult.getUserContext(); machineModel = machineName.split(" "); var valueArray = new Array(1); valueArray[0] = new Array(1); valueArray[0][0] = machineModel[0] + '\n' + machineModel[1]; range.setValuesAsync(valueArray, setMachineInput, range.getAddressA1());} // Call back function to handle updating the Machine Inputs when a// new machine has been selected in the machine drop downfunction setMachineInput(asyncResult){ rangeAddress = asyncResult.getUserContext(); if(rangeAddress == "'Data'!B6") resetModel(1); else if(rangeAddress == "'Data'!B7") resetModel(2); else if(rangeAddress == "'Data'!B8") resetModel(3); }

4. Add the following code underneath the comment // fillMachineDropdowns(). This function handles a couple of chores associated with populating the Machine drop-down controls and setting them to default values.

JavaScript

// Gets the information needed for the machine selection drop downs, and // creates the drop down list of available machinesfunction fillMachineDropdowns(call, values){ if(call == "get") xlWebPart.getActiveWorkbook().getRangeA1Async( "'Data'!AvailableMachines", getMachineInputRangeComplete,

Page 21: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

'AvailableMachines'); else if(call == "set") { for(var i = 0; i < values.length; i++) { // parse out new line escape character from model key for IE var machineName = values[i][0]; if(machineName.split("\n").length > 1) { var tempName = machineName.split("\n"); machineName = tempName[0] + ' ' + tempName[1]; } // add the model item to each of the three lists addItemToDropdown( machineName,"'Data'!B6",document.getElementById('machine1dd'));

addItemToDropdown( machineName,"'Data'!B7",document.getElementById('machine2dd'));

addItemToDropdown( machineName,"'Data'!B8",document.getElementById('machine3dd')); }

xlWebPart.getActiveWorkbook().getRangeA1Async( "'Data'!B6:B8", getMachineInputRangeComplete,'SelectedMachines'); } else { // Handles setting the drop down to the machine that is displayed // when the workbook is initially loaded for(i = 0; i < values.length; i++) { var machineName = values[i][0]; if(machineName.split("\n").length > 1) { var tempName = machineName.split("\n"); machineName = tempName[0] + ' ' + tempName[1]; } var ddIndex = i+1; var list = document.getElementById('machine'+ddIndex+'dd'); setSelectedDDItem(list, machineName); } }}

Page 22: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

5. Add the following code underneath the comment // setSelectedDDItem(). These are just a couple of helper functions to add an item to a drop-down list and to set the selected index of a drop-down list.

JavaScript

// Add item to a drop down objectfunction addItemToDropdown(text, value, list){ var opt = document.createElement("option"); opt.text = text; opt.value = value; list.options.add(opt); }

// Sets the selected index for a drop down objectfunction setSelectedDDItem(list, value){ if(list == null) return; for(var i = 0; i < list.options.length; i++) { if(list.options[i].text == value) { list.selectedIndex = i; break; } }}

Exercise 2 Verification

To check your work thus far, perform the following steps.

1. In Visual Studio 2010, press CTRL + S to save your work.

2. Open Internet Explorer and navigate to http://intranet.contoso.com/SiteAssets/

3. Click Add document

4. Click Browse and select the TCO.JS file in C:\Student\Excel Services

5. Click Open

6. Click OK to upload the document (make sure Overwrite existing files is checked)

7. Navigate to http://intranet.contoso.com/SitePages/TCO Model.aspx

Page 23: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

8. Click on Machine Inputs under the Model Navigation section

9. Double-click on the selling price associated with machine 1.

10. Edit the value so that it is $500,000. Excel Services recalculates the workbook with the new value.

11. Click on a different cell.

12. Click on the text “reset this item” above Machine 1.

13. Observe that the value reverts to its original value.

14. Click on the link named Show Machine Selection under the Other heading. Observe that the machine drop-down controls appear.

15. Change the machine selected for Machine 1. Observe that the model updates the Machine Inputs worksheet to reflect your selection.

Exercise 3: Interacting with the REST API and Excel Web Services

Thus far, the techniques demonstrated have used the JSOM exclusively. In order to round out solutions, you may find it necessary to utilize functionality provided by either the Excel Services REST API and/or the Excel Services Web Services. In Exercise 3, you will learn how to integrate both of these options with the use of the JSOM to round out a solution.

Note: Excel Services in Office 365 does not support the ability to call the Excel Web Services. Consequently, the technique demonstrated in Task 1 will not work in Office 365. Office 365 does support the Excel Services REST API. The technique demonstrated in Task 2 is appropriate for Office 365.

Task 1 – Implementing a File Save Feature

A primary expectation that people have when working with documents is the ability to save their changes. The Excel Web Services provides this functionality via either the SaveWorkbook method or the SaveWorkbookCopy method. You can call this method using JavaScript to implement this functionality.

1. Add the following code underneath the comment // createXmlDocument(). These are a couple utility functions that assist in the creation and transmission of a SOAP request.

JavaScript

//Creates a XmlHttp object for the SOAP requestfunction createXmlHttp()

Page 24: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

{ var xmlHttp = null; if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlHttp;}

//Creates a XmlDocument object for the SOAP envelopefunction createXmlDocument(){ var doc = null; if (document.implementation && document.implementation.createDocument) { doc = document.implementation.createDocument("", "", null); } else { doc = new ActiveXObject("MSXML2.DOMDocument"); } return doc;}

2. Add the following code underneath the comment // clearSaveResults(). The function saveWorkbookCopyAsync does all the heavy lifting when it comes to implementing the save functionality. This function makes a call into Excel Web Services to access the SaveWorkbookCopy method. The important thing here is that you use the session ID associated with the Excel Web Access web part so that when the call to SaveWorkbookCopy is made, Excel Services knows that is should save a copy with the transient values used in the session associated with the Excel Web Access web part. Note that this bit of code assumes you are saving to a document library at http://intranet.contoso.com/Shared%20Documents. Update the URL specified in the SOAP message as required for your environment.

JavaScript

// Saves a copy of the workbook through the use of Excel Services and SOAPfunction saveWorkbookCopyAsync(action){ if(action == 'cancel')

Page 25: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

{ document.getElementById('savediv').style.display = 'none'; return; } var fileName = document.getElementById('fileName').value; var doc = createXmlDocument(); var xmlHttp = createXmlHttp(); var sessionId = om.getActiveWorkbook().getSessionId(); // SOAP envelope for SaveWorkbookCopy request var xml = '<?xml version="1.0" encoding="utf-8"?>' + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + 'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' + 'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' + '<soap:Body>' + '<SaveWorkbookCopy ' + 'xmlns="http://schemas.microsoft.com/office/excel/server/webservices">' + '<sessionId>' + sessionId + '</sessionId>' + '<workbookPath>' + 'http://intranet.contoso.com/Shared%20Documents/' + fileName + '.xlsx</workbookPath>' + '<workbookType>FullWorkbook</workbookType>' + '<saveOptions>AllowOverwrite</saveOptions>' + '</SaveWorkbookCopy>' + '</soap:Body>' + '</soap:Envelope>'; doc.loadXML(xml); xmlHttp.open("POST", "/_vti_bin/ExcelService.asmx", true); xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); xmlHttp.setRequestHeader("Content-Length", doc.length); xmlHttp.setRequestHeader( "SOAPAction", "\"http://schemas.microsoft.com/office/excel/server/webservices/SaveWorkbookCopy\""); xmlHttp.onreadystatechange = function()

Page 26: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

{ // If the workbook is saved successfully, display the result if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { document.getElementById('savediv').style.display = 'none'; document.getElementById('saveresult').innerHTML = '<b style="color:#018FC3;">' + fileName + '.xlsm saved successfully.</b>'; //Clear the result setTimeout(clearSaveResults,5000); } } xmlHttp.send(doc.xml);} // Clears the result of the SaveWorkbookCopy requestfunction clearSaveResults(){ document.getElementById('saveresult').innerHTML = '';}

Task 2 – Enhancing the UI with a Chart

Excel support for creating charts and tables of data is one of the traits that make it such a wonderful data analysis tool. Using the Excel Services REST API, you can extract this type of information from a workbook for reuse in other applications. In the TCO model for example, the desired product of the calculations is a chart that compares the total cost of ownership for the three selected machines. Rather than having to navigate between the inputs and the outputs as you make changes, a more convenient option is to display the output at all times so that you can see the results of your changes as you make them.

1. Add the following code underneath the comment // getChartImage().

JavaScript

// Gets the chart information located within the current session and uses the // REST API to retrieve a chart with those input values from the stored workbook. function getChartImage(call, values){ if(call == "get") xlWebPart.getActiveWorkbook().getRangeA1Async( "'TCO Detailed Results'!D9:F17", getMachineInputRangeComplete,"MachineTotalCosts"); else if(call == "set") { var chartUrlTemp = chartUrl;

Page 27: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

// Create URL for REST API chartUrlTemp += 'Ranges%28%27%27TCO%20Detailed%20Results%27!D17%27%29=' + values[8][0];

chartUrlTemp += '&Ranges%28%27%27TCO%20Detailed%20Results%27!E17%27%29=' + values[8][1];

chartUrlTemp += '&Ranges%28%27%27TCO%20Detailed%20Results%27!F17%27%29=' + values[8][2];

chartUrlTemp += '&Ranges%28%27%27Machine%20Inputs%27!E12%27%29=' + values[0][0];

chartUrlTemp += '&Ranges%28%27%27Machine%20Inputs%27!F12%27%29=' + values[0][1];

chartUrlTemp += '&Ranges%28%27%27Machine%20Inputs%27!G12%27%29=' + values[0][2];

document.getElementById('chartimg').innerHTML = '<img src=\'' + chartUrlTemp + '\' width="300px" height="300px" />'; }}

2. Locate the GetEwa() function you added in Exercise 1, Task 2, Step 3 and modify the line // TO IMPLEMENT: getChartImage(“get”); as shown below.

JavaScript

getChartImage("get");

3. Add a new script level variable underneath the var xlWebPart script level variable as shown below.

JavaScript

// SCRIPT LEVEL VARIABLESvar xlWebPart;var chartUrl = 'http://intranet.contoso.com/_vti_bin/ExcelRest.aspx/Shared%20Documents/' +

Page 28: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

'Contoso%20TCO.xlsx/Model/Charts%28%27Chart%203%27%29?';

Exercise 3 Verification

To check your work, perform the following steps.

1. In Visual Studio 2010, press CTRL + S to save your work.

2. Open Internet Explorer and navigate to http://intranet.contoso.com/SiteAssets/

3. Click Add document

4. Click Browse and select the TCO.JS file in C:\Student\Excel Services

5. Click Open

6. Click OK to upload the document (make sure Overwrite existing files is checked)

7. Navigate to http://intranet.contoso.com/SitePages/TCO Model.aspx

8. Verify that a chart from the workbook now appears in the upper-left portion of the browser window.

Figure 4

Page 29: Designing Excel Solutions for the Webaz12722.vo.msecnd.net/.../Lab.docx · Web viewExcel Services, part of SharePoint Server 2010, offers new capabilities to developers looking to

Model Navigation – TCO Calculator

9. Click on Save Workbook Copy. Verify that an additional bit of UI appears in the Content Editor Web part.

Figure 6Save Workbook Copy

10. Click Save

11. Navigate to the Shared Documents library (refresh the page if it was already open).

12. Verify that a copy of the workbook is in the library.

Summary

The programmability story around Excel Services, part of SharePoint Server 2010, has increased dramatically versus the prior version. In addition to expanded capabilities of the Excel Web Services, there is a REST API for accessing resources in Excel workbooks using a URL and an ECMAScript or JavaScript object model (JSOM). You can use all three options within a single solution to create sophisticated web-based applications that leverage the power of Microsoft Excel.