This topic has not yet been rated - Rate this topic

Using Visual Studio to create a task pane or content app

apps for SharePoint

Published: February 26, 2013

How to

Learn how to use Visual Studio 2012 to develop an app for Office for Word 2013, Excel 2013, or Microsoft Project Professional 2013.

In this article
Create an app for Office project
Modify the settings of the app
Develop the contents of your app
Debug the app
Publish your app

You can use Visual Studio to create apps for Office. Just choose a template and select a few options in a wizard. Visual Studio generates everything you need to run your app immediately. The only thing that you have to add is the content that appears in the app.

This topic focuses on the Visual Studio experience. However, it does contain sample code. The sample used in this topic shows a calculator that enables users to perform basic math functions by using data in a document. Users can choose a button in the app to put calculated values back into the document.

You can get started quickly by using the Apps for Office project template in Visual Studio.

To create an app for Office project

  1. Start Visual Studio.

  2. On the menu bar, choose File, New, Project.

    The New Project dialog box opens.

  3. In the templates pane, under the node for the language you want to use, expand Office SharePoint.

  4. In the list of project types for Apps, choose Apps for Office.

  5. In the Name box, enter a name for the project.

    By default, the project name is also used as the solution name.

  6. In the Location box, enter the path where you want to create the project, and then choose the OK button.

    The Create app for Office dialog box opens.

  7. In the Create app for Office dialog box, choose whether you want to create a task pane app or a content app. If you choose a task pane app, select the host applications (for example, Word, Excel, or project) in which you want the app to appear.

    To help you decide which type of app to choose, see Types of apps for Office.

  8. Choose the Finish button.

    When you complete the wizard, Visual Studio creates a solution. The solution contains an app project and an ASP.NET web application project.

  • The app project contains only an XML manifest file. Visual Studio generates the contents of this file for you. Therefore, you can run the project and use your app without adding anything else to this file.

  • The web application project contains the content pages of your app. It contains all of the files and file references that you need to develop Office-aware HTML and JavaScript pages. While you develop your app, Visual Studio hosts the web application on your local IIS server.

If you want to learn more about ASP.NET web application projects, see ASP.NET Web Projects.

Your app project contains settings that describe how your app should be activated when an end user installs and uses it. You can use a property page-like editor to provide values for the most common settings such as which page appears when the app is activated or the text used to describe your app to potential users.

For advanced settings, such as the target locale of the app, edit the XML manifest file of the project directly.

Manifest editor

You can open the manifest editor from Solution Explorer. Just expand the app project node, choose the folder that contains the XML manifest, and then choose the ENTER key.

The following table describes the fields that appear in the manifest editor.

Property

Corresponding value in the XML manifest file

Description

Display Name

DefaultValue attribute of the DisplayName element.

The name that appears in the UI of the host application. For example, in Excel, when a user chooses Insert, App, this name appears in the list of available apps. This name can also appear as a title above the app.

App type

The OfficeApp complexType.

The type of the app. A value of TaskPaneApp indicates that the app appears in the task pane of the Office application. A value of ContentApp indicates that the app appears in the body of a document.

Version

The Version element.

Specifies the version of the app.

Provider name

The ProviderName element.

Specifies the name of the individual or company that developed the app.

Description

DefaultValue attribute of the Description element.

The description that appears when a user points to the app name in the list of available apps.

Icon

DefaultValue attribute of the IconUrl element.

The image that appears for your app in the ribbon of the host application.

Source Location

DefaultValue attribute of the SourceLocation element.

The location of the first page that appears in the app when it is activated in the host application. The default value of this property is the default HTML file of your project.

Capabilities

The Capabilities element.

The host application that this app supports.

Permissions

The Permissions element.

The permissions required by this app.

App Domains

The AppDomains element.

Specifies additional domains that this app will use to load pages.

XML manifest

You can open the XML manifest file from Solution Explorer. Just expand the app project node, expand the folder that contains the XML manifest, and then choose the XML manifest.

Visual Studio generates the contents of this file for you. You can point to any element in the file to view a tooltip that describes the purpose of the element. For a complete list of descriptions, see Apps for Office XML manifest overview.

While the app project publishes the settings that describe your app, the web application provides the content that appears in the app.

The web application project contains a default HTML page and JavaScript file that you can use to get started. The project also contains a JavaScript file that is common to all pages that you add to your project. These files are convenient because they contain references to other JavaScript libraries including the JavaScript API for Office. The following table describes these files.

File

Description

Home.html

Located in the Home folder of the project, this is default HTML page of the app. This page appears as the first page inside of the app when it is activated in a document. This file is convenient because it contains all of the file references that you need to get started.

Home.js

Located in the Home folder of the project, this is the default JavaScript file of the page. This file contains some example code to get you started.

App.js

Located in the App folder of the project, this is the default JavaScript file of the app. This file contains some example code to get you started.

Note Note

You do not have to use these files. Feel free to add other files to the project and use those instead. If you want another HTML file to appear as the initial page of the app, open the manifest editor, and then point the SourceLocation property to the name of the file.

Default HTML file

When it’s time to create the UI of your app, the default HTML page is a great place to start. You can open the default HTML file from Solution Explorer. Just expand the web application project folder, expand the App folder, expand the Home folder, and then chooseHome.html. Then, on the View menu, choose Code.

The <head> element of the page refers to several files. The following table describes each of them.

File

Description

Office.css

Contains style definitions that help your app have the same look and feel of the host application.

App.css

Contains any styles that you want to add. This is just a start page. By default, it is empty.

MicrosoftAjax.js

Defines language extensions that are supported by the Microsoft Ajax library. This file is included in the project because the Office.js file consumes it. However, you can use functions in this file directly if you want.

For more information about the functions, types, and fields of the library, see Microsoft Ajax Library Client Reference. To learn about Microsoft Ajax in general, see Inside the Microsoft Ajax Library.

Office.js

Contains the JavaScript API for an app for Office. This file provides your code with an entry point into documents.

For more information about the functions, types, and fields in this file, see the JavaScript API for Office.

jquery-1.7.1.js

Contains a JavaScript library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.

Add code to the default html file

The following HTML creates a calculator.

<body>
    <!-- Page content -->
    <div id="content-header">
        <div class="padding">
            <h1>Calculator</h1>
        </div>
    </div>
    <div id="content-main">
        <div class="padding">
            <div id="output">
                <span id="stored-data" style="font-size:medium"></span>
<br />
                <span id="entered-data">0</span>
            </div>
            <hr />
            <br />
            <div id="buttons" style="text-align:center;">
                <!-- First row of buttons: C/EC, MSR, M-, M+ -->
                <input id="clear" type="button" value="CE" onclick="clearEntries()"/>
                <input id="memory" type="button" value="MSR" />
                <input id="memory-minus" type="button" value="M-" />
                <input id="memory-plus" type="button" value="M+" />
                <br />
                <!-- Second row of buttons: 7, 8, 9, '/' -->
                <input id="7" type="button" value="7" onclick="includeNumber(this)"/>
                <input id="8" type="button" value="8" onclick="includeNumber(this)"/>
                <input id="9" type="button" value="9" onclick="includeNumber(this)"/> 
                <input id="divide" type="button" value="/" onclick="includeOperator(this)"/>
                <br />
                <!-- Third row of buttons: 4, 5, 6, '*' -->
                <input id="4" type="button" value="4" onclick="includeNumber(this)"/>
                <input id="5" type="button" value="5" onclick="includeNumber(this)"/>
                <input id="6" type="button" value="6" onclick="includeNumber(this)"/> 
                <input id="multiply" type="button" value="*" onclick="includeOperator(this)"/>
                <br />
                <!-- Fourth row of buttons: 1, 2, 3, '-' -->
                <input id="1" type="button" value="1" onclick="includeNumber(this)"/>
                <input id="2" type="button" value="2" onclick="includeNumber(this)"/>
                <input id="3" type="button" value="3" onclick="includeNumber(this)"/> 
                <input id="minus" type="button" value="-" onclick="includeOperator(this)"/>
                <br />
                <!-- Fifth row of buttons: 0, '.', '+', '=' -->
                <input id="0" type="button" value="0" onclick="includeNumber(this)"/>
                <input id="decimal" type="button" value="." onclick="includeNumber(this)"/>
                <input id="plus" type="button" value="+" onclick="includeOperator(this)"/> 
                <input id="equals" type="button" value="=" onclick="evaluate()"/> 
            </div>
<br />
            <hr />
            <br />
            <div id="content-buttons" style="text-align:center"></div>
        </div>
    </div>
</body>

Default JavaScript file

You can open the default JavaScript file of your page from Solution Explorer. Just expand the web application project folder, expand the App folder, expand the Home folder, and then choose Home.js. Then, on the View menu, choose Code.

This file contains a declaration of the initialize event of the Office object. You can place any code inside this event that you want to run when the app is loaded. By default, this method contains sample code.

This code adds a button to the app that enables you to get data from information that you select in a document

Add code to the default JavaScript file

The following JavaScript adds the functions that are called in the Home.html file. This provides the functionality that enables users to perform the basic math functions of the sample calculator. Users can use buttons to get data from the hosting document and use that data in their calculations. Then, users can put calculated values back into the document.

var output;
var storedData;
var enteredData;
var storedOperation = [];

(function () {
    "use strict";
    
    // The initialize function must be run each time a new page is loaded
    Office.initialize = function (reason) {
        $(document).ready(function () {
            app.initialize();
            
            initializeCalculator();
        });
    };
        
    function initializeCalculator() {
        // Check if getting and setting the selection is supported, and add appropriate functionality
        if (Office.context.document.setSelectedDataAsync) {
            var $setData = $('<input type="button" style="width:47%; margin:2px;" value="Write to selection" />')
                .appendTo($('#content-buttons'));
            $setData.click(setData);
        }  
        
        if (Office.context.document.getSelectedDataAsync){
            var $getData = $('<input type="button" style="width:47%; margin:2px;" value="Read selection" />')
                .appendTo($('#content-buttons'));
            $getData.click(getData);
        }
        
        // Capture div references and initialize variables
        output = document.getElementById('output');
        storedData = document.getElementById('stored-data');
        enteredData = document.getElementById('entered-data');
        storedOperation[0] = 'undefined';
        storedOperation[1] = 'undefined';
    }
    
    // Inserts the current entered data/ result into 
    // the currently selected place in the document.
    function setData() {
        // Get the current value in the entereddata div.
        var value = enteredData.innerText;
    
        // Set the selected data into the document as text.
        Office.context.document.setSelectedDataAsync(value, function (result) {
            if (result.status === Office.AsyncResultStatus.Failed) {
                app.showNotification(result.error.name, result.error.message);
            }
        });
    }
    
    // Gets data from the current document and returns it as a number.
    function getData() {
        var dataValue = 0;
    
        // Get the current selection from the document.
        Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
            function (result) {
                if (result.status === Office.AsyncResultStatus.Succeeded) {
                    var results = result.value;
                    results = parseFloat(results);
    
                    if (isNaN(results)) {
                        app.showNotification('Invalid number', result.value);
                    } else {
                        dataValue = results;
                    }
                } else {
                    app.showNotification(result.error.name, result.error.message);
                }
                enteredData.innerText = dataValue;
            }
        );
    }
})();


////////////////////////////////////////////////////////////////
//        Functions called directly from HTML elements:
////////////////////////////////////////////////////////////////
    
// Add numbers to the number display.
function includeNumber(node) {

    var newEntry = node.id;
    var dataEntry = enteredData.innerText;
    dataEntry = String(dataEntry);

    // Check to see if the decimal button was clicked
    // and that there are no other decimals in the entry.
    if (newEntry == 'decimal') {
        if (dataEntry.indexOf('.') == -1) {
            newEntry = '.';
        }
        else {
            newEntry = '';
        }
    }

    // Add the new entry to the entered data.
    if (enteredData.innerText == '0') {
        enteredData.innerText = newEntry;
    }
    else {
        enteredData.innerText += newEntry;
    }
}

// Convert the information in the display to a number
// and store both operand and operator.
function includeOperator(node) {

    if (storedOperation[1] == 'undefined') {

        // Parse the value and operator for the operation.
        var operator = node.id;
        var operand = enteredData.innerText;
        var operation;

        operand = parseFloat(operand);

        // Store the operation as an anonymous function 
        // in the global variable storedOperation.
        switch (operator) {
            case "divide":
                operation = function (x, y) { return x / y };
                storedData.innerText = operand + " / ";
                break;

            case "multiply":
                operation = function (x, y) { return x * y };
                storedData.innerText = operand + " * ";
                break;

            case "minus":
                operation = function (x, y) { return x - y };
                storedData.innerText = operand + " - ";
                break;

            case "plus":
                operation = function (x, y) { return x + y };
                storedData.innerText = operand + " + ";
                break;
        }

        // Store the entered data and the operator into a global variable.
        // Reset the innerText of the enteredData span.
        storedOperation[0] = operand;
        storedOperation[1] = operation;
        enteredData.innerText = "0";
    }
}

// Removes all entries from the output and sets the value to '0'.
function clearEntries() {
    enteredData.innerText = '0';
    storedData.innerText = '';
}

// Gets the data and operation stored in the global array,
// evaluates the expression, and returns the results.
function evaluate() {

    // Ensure that some data is stored already before attempting to evaluate.
    if (storedOperation[0] != 'undefined') {

        // Define the two operands and operation to perform.
        var x = storedOperation[0];
        var y = enteredData.innerText;
        y = parseFloat(y);
        var operation = storedOperation[1];
        var result;

        result = operation(x, y);
        result = result.toFixed(5);

        // Display results and clear the stored data span.
        enteredData.innerText = result;
        storedData.innerText = '';

        // Clear the data out of the storedOperation array.
        storedOperation[0] = 'undefined';
        storedOperation[1] = 'undefined';
    }
}


When you are ready to start your app, review build and debug related properties, and then decide whether you want to test your app by using an existing document. Then, start the solution.

Review the build and debug properties

Before you start the solution, it’s a good idea to be sure that Visual Studio will open the host application that you want. That information appears in the property pages of the project along with several other properties that relate to building and debugging the app.

To open the property pages of a project, perform the following steps:

  1. In Solution Explorer, choose the project name.

  2. On the menu bar, choose View, Properties Window.

The following table describes the properties of the project.

Property

Description

Start Action

Specifies what document to open when you start the project.

Web Project

Specifies the name of the web project associated with the app.

Use an existing document to debug the app

You can add documents to the app project. That way, if you have a document that contains test data that you want to use with your app, Visual Studio will open that document for you when you start the project.

To use an existing document to debug the app

  1. In Solution Explorer, choose the app project folder.

    Note Note

    Be sure to choose the app project and not the web application project.

  2. On the Project menu, choose Add Existing Item.

  3. In the Add Existing Item dialog box, locate and select the document that you want to add.

  4. Choose the Add button to add the document to your project.

  5. In Solution Explorer, open the shortcut menu for the project, and then choose Properties.

    The property pages for the project appear.

  6. In the Start Action list, choose the document that you added to the project, and then choose the OK button to close the property pages.

Start the solution

Visual Studio will automatically build the solution when you start it. You can start the solution from the Menu bar by choosing Debug, Start.

Note Note

If script debugging isn't enabled in Internet Explorer, you won't be able to start the debugger in Visual Studio. You can enable script debugging by opening the Internet Options dialog box, choosing the Advanced tab, and then clearing the Disable Script Debugging (Internet Explorer) and Disable Script Debugging (Other) check boxes.

Visual Studio builds the project and performs the following actions.

  1. Creates a copy of the XML manifest file and adds it to ProjectName\Output directory. The host application consumes this copy when you start Visual Studio and debug the app.

  2. Creates a set of registry entries on your computer that enable the app to appear in the host application.

  3. Builds the web application project, and then deploys it to the local IIS web server (http://localhost).

After Visual Studio builds the project, Visual Studio performs the following actions.

  1. Modifies the SourceLocation element of the XML manifest file by replacing the ~remoteAppUrl token with the fully qualified address of the start page (for example, http://localhost/MyAgave.html).

  2. Starts the web application project in IIS Express.

  3. Opens the host application.

Visual Studio doesn't show validation errors in the OUTPUT window when you build the project. Visual Studio reports errors and warnings in the ERRORLIST window as they occur. Visual Studio also reports validation errors by showing wavy underlines (known as squiggles) of different colors in the code and text editor. These marks notify you of problems that Visual Studio detected in your code. For more information, see Code and Text Editor. For more information about how to enable or disable validation, see the following topics:

To review the validation rules of the XML manifest file in your project, see Apps for Office XML manifest overview.

Show an app in Excel, Word, or Project and step through your code

If you set the Start Action property of the app project to Excel or Word, Visual Studio creates a new document and the app appears. If you set the Start Action property of the app project to use an existing document, Visual Studio opens the document, but you have to insert the app manually. If you set the Start Action to Microsoft Project, you also have to insert the app manually.

To show an app for Office in Excel or Word

  1. In Excel or Word, on the Insert tab, choose Apps for Office.

  2. In the list that appears, choose your app.

To show an app for Office in Project

  1. In Project, on the Project tab, choose Apps for Office.

  2. In the list that appears, choose your app.

In Visual Studio, you can then set break-points. Then, as you interact with your app and step through the code in your HTML, JavaScript, and C# or VB code files.

Modify code and continue to debug the app without having to start the project again

You can change your code and review the effects of those changes in your app without having to close the host application and start the project again. After you change your code, open the shortcut menu for the app, and then choose Reload. When you reload the app it becomes disconnected with the Visual Studio debugger. Therefore, you can view the effects of your change, but you cannot step through your code again until you attach the Visual Studio debugger to all of the available iexplore.exe processes.

To attach the Visual Studio debugger to all of the available iexplore.exe processes

  1. In Visual Studio, choose DEBUG, Attach to Process.

  2. In the Attach to Process dialog box, choose all of the available iexplore.exe processes, and then choose the Attach button.

For more information about how to publish your app, see How to: Publish an app for Office.

Did you find this helpful?
(1500 characters remaining)

Community Additions

ADD
© 2013 Microsoft. All rights reserved.