Search This Blog

Monday, 20 January 2014

How to: Create your first task pane or content app by using Visual Studio

           
 
Published: 2013/11/15
This topic shows you how to use Visual Studio to create a Hello World app for Office and then extend it to read, write, and bind to the document.
Applies to: apps for Office | Office 2013 | Office 365 | Excel Web App | Word 2013 | Excel 2013 | PowerPoint 2013
Install the following components before you get started to First task - Visual Studio
  • Microsoft Visual Studio 2013
    -or-
    Visual Studio 2012 and the Microsoft Office Developer Tools for Visual Studio 2012.
    To download Visual Studio 2012, see "Tools" on the Download page.
    To download Visual Studio 2013, see the Visual Studio Downloads page
  • Word 2013
  • Excel 2013
We'll start by creating and running a Hello World task pane app in Excel. Then we'll extend the app to perform the following tasks:
  • Write data to the current selection in the worksheet.
  • Read data from the current selection in the worksheet and display it in the app UI.
  • Create a binding to the current selection in the worksheet.
  • Read the data in the binding and display it in the app's UI.
  • Add an event handler to read and display data whenever data in the binding is changed.
Finally, we'll make changes to some project settings and the manifest to do the following:
  • Run the task pane app in Word.
  • Run the app as a content app in Excel.
To get started, create an Apps for Office project in Visual Studio.

To create a project in Visual Studio

  1. Start Visual Studio.
  2. On the File menu, choose New Project.
    The New Project dialog box opens.
  3. In the list of project types under Visual C# or Visual Basic, expand Office/SharePoint, choose Apps, and then choose App for Office 2013.
  4. Name the project HelloWorld, and then choose OK.
    The Create App for Office dialog box opens. By default, the option Task pane app in is selected along with the check boxes for Excel, Word, PowerPoint, and Project. That's what we want, so leave that option selected, and then choose Finish.
    Visual Studio creates the project, and its files appear in Solution Explorer.
    The default HelloWorld.html and HelloWorld.js pages of the project open in the Source view of the Visual Web Developer designer.
To design the appearance of the app, you add HTML to the default page of the project. To design the functionality and programming logic for your app, you can add JavaScript code directly in the HTML page, or to the default JavaScript file (HelloWorld.js).

To create a Hello World app (First Task)

  1. In the designer, choose the Source tab if the editor isn't already in HTML Source view.
  2. Delete the tags inside the opening and closing <body> tags, and then type <div>Hello World!</div> inside the opening and closing body tags.

  3. <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
        <title>HelloWorld</title>
    
        <link rel="stylesheet" type="text/css" href="../Content/Office.css" />
        <link rel="stylesheet" type="text/css" href="../Content/App.css" />
    
        <script src="../Scripts/jquery-1.6.2.js"></script>
        <script src="../Scripts/Office/MicrosoftAjax.js"></script>
        <script src="../Scripts/Office/Office.js"></script>
    
        <!-- Add your JavaScript to the following file -->
        <script src="../Scripts/HelloWorld.js"></script>
      </head>
      <body>
        <div>Hello World!</div>
      </body>
    </html>
    
  4. On the Debug menu, choose Start Debugging or press the F5 key.
    Excel opens a blank workbook and app appears in the task pane.
    Figure 1. Hello World task pane app

    Hello World task pane app
  5. Close the workbook file.
    Debugging stops and focus returns to Visual Studio.
In the following procedures, we'll extend your Hello World app to access data in the worksheet.

To write data to the worksheet

  1. Replace <div>Hello World!</div> inside the opening and closing <body> tags of the HelloWorld.html page with the following HTML.
        <button onclick="writeData()"> Write Data </button><br/>
        <button onclick="readData()"> Read Selected Data </button><br/>
        <button onclick="bindData()"> Bind Selected Data </button><br/>
        <button onclick="readBoundData()"> Read Bound Data </button><br/>
        <button onclick="addEvent()"> Add Event </button><br/>
        <span>Results: </span><div id="results"></div>
    
    
    This adds some buttons to perform data access actions and a div to display results in the app's HTML page. Next, we'll write the writeData() function to write sample text to the current selection.
  2. Open the HelloWorld.js file to display the default JavaScript file for the app. If it's not already open, you can find it in Solution Explorer under Scripts > Office.
  3. Add the following functions to the HelloWorld.js file.
    function writeData() {
        Office.context.document.setSelectedDataAsync("Hello World!", function (asyncResult) {
            if (asyncResult.status === "failed") {
                writeToPage('Error: ' + asyncResult.error.message);
            }
        });
    } 
    function writeToPage(text) {
        document.getElementById('results').innerText = text;
    }
    
    NoteNote
    Make sure not to delete or overwrite the Office.initialize event handler function (although you can replace the code within it). The Office.initialize event handler must be in place for your app to initialize correctly at runtime.
    The code in the writeData() function calls the document.setSelectedDataAsync method to write "Hello World!" to the current cell when you choose the Write Data button. Most of the methods used in this walkthrough are asynchronous, which is why their names end with "Async", and callback functions like the anonymous function passed as the argument following "Hello World!" are used. For more information about using "Async" methods, see Asynchronous programming in apps for Office.
    The writeToPage(text) function is a helper function for writing text back to the results div on the app HTML page. The writeToPage(text) function is also used to display data and messages in the code examples in the following procedures.
  4. On the Debug menu, choose Start Debugging or press the F5 key.
  5. Choose the Write Data button to write "Hello World!" to the current cell, but don't close the workbook or stop debugging yet.
    Figure 2. Write text

    Write text
  6. Switch back to the code editor, and replace "Hello World!" in the call to the setSelectedDataAsync method with [["red"],["green"],["blue"]] like this:
    function writeData() {
        Office.context.document.setSelectedDataAsync([["red"],["green"],["blue"]], function (asyncResult) {
            if (asyncResult.status === "failed") {
                writeToPage('Error: ' + asyncResult.error.message);
            }
        });
    }
    
    Writing an array of arrays like [["red"],["green"],["blue"]] creates what's called a matrix data structure, which in this case creates a single column of three cells (rows). You can create a matrix of two columns of three rows like this:
    [["red", "rojo"],["green", "verde"],["blue", "azul"]]
    You can create a single row of three cells like this:
    [["red","green","blue"]]
  7. Choose Ctrl+S to save this change to the code.
  8. Now switch back to the workbook, open the shortcut menu (right-click) for the app task pane, and then choose Reload.
    This reloads the HTML page with the updated JavaScript code.
  9. Move the selection to a new cell, and then choose the Write Data button.
    This writes the array containing red, green, and blue to a single column of three cells.
    Figure 3. Write matrix

    Write matrix
  10. Close the workbook to stop debugging.

To read data from the worksheet

  1. In Solution Explorer, open the HelloWorld.js file.
  2. Add the following code to the HelloWorld.js file below the functions you added in the previous procedure.
    function readData() {
        Office.context.document.getSelectedDataAsync("matrix", function (asyncResult) {
            if (asyncResult.status === "failed") {
                writeToPage('Error: ' + asyncResult.error.message);
            } 
            else{
                writeToPage('Selected data: ' + asyncResult.value);
            }
        });
    }
    
    
    The readData() function calls the document.getSelectedDataAsync method to read the data that's currently selected by the user as a "matrix" coercionType, which is a 2-D array. For Excel, this will read a contiguous range of one or more cells.
  3. On the Debug menu, choose Start Debugging or press the F5 key.
  4. Choose the Write Data button, leave the three cells that have red, green, and blue in them selected, and then choose the Read Selected Data button.
    This reads the data from the three cells as a matrix data structure, and then writes those values to the app page.
    Figure 4. Read matrix

    Read matrix
  5. Close the workbook to stop debugging.

To create a binding for selected data and read the bound data

  1. In Solution Explorer, open the HelloWorld.js file.
  2. Add the following code to the HelloWorld.js file below the function you added in the previous procedure.
    function bindData() {
        Office.context.document.bindings.addFromSelectionAsync("matrix", { id: 'myBinding' }, 
            function (asyncResult) {
                if (asyncResult.status === "failed") {
                    writeToPage('Error: ' + asyncResult.error.message);
                } else {
                    writeToPage('Added binding with type: ' + asyncResult.value.type + ' and id: ' +
                        asyncResult.value.id);
                }
            });
    }
    
    The bindData() function calls the bindings.addFromSelectionAsync method to create a matrix binding with an id of myBinding that is associated with the cells that the user selected. You can specify the bindingType as "text" to create a binding to a single cell in Excel, or to run of characters (a string) in a Word document. For more information about bindings, see Binding to regions in a document or spreadsheet.
  3. Add the following code to the HelloWorld.js file below the bindData () function.
    function readBoundData() {
        Office.select("bindings#myBinding").getDataAsync({ coercionType: "matrix" }, 
            function (asyncResult) {
                if (asyncResult.status === "failed") {
                    writeToPage('Error: ' + asyncResult.error.message);
                } else {
                    writeToPage('Selected data: ' + asyncResult.value);
                }
            });
    }
    
    The readBoundData() function calls the Office.select method to get the binding created by the bindData() function, which has an id of myBinding. (Alternatively, you can use the bindings.getBindingByIdAsync method to access a binding by its id.) The function then calls the Binding.getDataAsync method to read the data from the binding. Because the binding is a matrix binding, you must specify the coersionType as "matrix" for the call to succeed.
  4. On the Debug menu, choose Start Debugging or press the F5 key.
  5. Choose the Write Data button, leave three cells that have red, green, and blue in them selected, and then choose the Bind Selected Data button.
    This creates a matrix binding that is associated with the three selected cells that have the id myBinding.
    Figure 5. Create a binding

    Create a binding
  6. Move the selection off of the three cells, and then choose the Read Bound Data button.
    This will read the data from the binding created in the previous procedure, and then write those values to the app page. If you didn't change the values, red, green, and blue will be displayed in the app.
  7. Change one or more values in the three cells, press the Enter key after each change, and then choose Read Bound Data again.
    This will read the changed data and display it in the app.
    Figure 6. Read from binding

    Read from binding
  8. Close the workbook to stop debugging.
Now let's add an event handler that will read and display the data in the binding whenever it is changed.

To add an event handler

  1. In Solution Explorer, open the HelloWorld.js file.
  2. Add the following code to HelloWorld.js file below the functions you added in the previous procedure.
    function addEvent() {
        Office.select("bindings#myBinding").addHandlerAsync("bindingDataChanged", myHandler, function (asyncResult) {
            if (asyncResult.status === "failed") {
                writeToPage('Error: ' + asyncResult.error.message);
            } else {
                writeToPage('Added event handler');
            }
        });
    }
    function myHandler(eventArgs) {
        eventArgs.binding.getDataAsync({ coerciontype: "matrix" }, function (asyncResult) {
    
            if (asyncResult.status === "failed") {
                writeToPage('Error: ' + asyncResult.error.message);
            } else {
                writeToPage('Bound data: ' + asyncResult.value);
            }
        });
    }
    
    
    The addEvent() function calls the Office.select method to get the myBinding binding object, and then calls the Binding.addHandlerAsync method to add an event handler for the Binding.DataChanged event. The myHandler function uses the binding property of the BindingDataChangedEventArgs object to access the binding that raised the event, and then calls the Binding.getDataAsync method to read and display the data when the event occurs.
  3. On the Debug menu, choose Start Debugging or press the F5 key.
  4. Choose the Write Data button, leave three cells that have red, green, and blue in them selected, and then choose the Bind Selected Data button.
  5. Choose the Add Event button.
    This retrieves the binding with id of myBinding, and then adds the myHandler function as the handler for the DataChanged event.
  6. Change one or more values in the three bound cells, and press the Enter key after each change.
    This will read the changed data and display it in the app task pane.
    Figure 7. Handling the DataChanged event

    Handling the DataChanged event
  7. Close Excel to stop debugging.
In the next section we'll modify the app project so that you can run and test it in Word.
You can perform the following steps to modify this app project so that it will run and debug in Word 2013.
  • Change the Start Action property of the project to start Word when debugging.
  • Run and debug in Word.

To change the Start Action property in the Debugging property page of the project

  1. In Solution Explorer, choose the project name (HelloWorld).
    The Project Properties property page for the project appears in the pane below the Solution Explorer.
  2. Under App, in the Start Action list, choose Microsoft Word.
    Figure 8. Setting the Start Action

    Setting the Start Action

To debug the app in Word

  • On the menu bar, choose Debug, Start Debugging.
    Word 2013 opens with the HelloWorld app in the task pane.
  • Click the Write Data, Read Selected Data, Bind Selected Data, Read Bound Data, and Add Event buttons to perform the same actions as when working in Excel.
    NoteNote
    In Word, the event handler won't run to display the bound data until you move the cursor outside of the table inserted by the Write Data button.
    Figure 9. Debugging in Word

    Debugging in Word
You can perform the following steps to modify this app project so that it will run as a content app in Excel.
  • Modify the manifest file to set the xsi:type attribute to "ContentApp" in the OfficeApp element.
  • Modify the manifest file to set values for the RequestedWidth and RequestedHeight elements.
  • Modify the manifest file to remove the "Presentation", "Project", and "Document"Capability elements from the Capabilities element.
  • Change the Start Action property of the project to start in Excel.

To modify the manifest file

  1. In Solution Explorer, open the HelloWorld.xml file.
  2. In the opening OfficeApp tag, change the value of the xsi:type attribute to "ContentApp".
    <OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ContentApp">
    
    The xsi:type attribute specifies the type of app for Office, which determines how the app runs when the user inserts it into a document or workbook. The previous value, "TaskPaneApp", specifies that the app runs in a task pane. Changing xsi:type to "ContentApp" specifies that the app runs in line with the workbook content as a content app.
    NoteNote
    In this release of Office, content apps can run only in Excel 2013 and Excel Web App. After you change xsi:type to "ContentApp" in the manifest, the app will run only in Excel 2013 or Excel Web App.
  3. Add the following RequestedWidth and RequestedHeight elements in the manifest within the <DefaultSettings> tags.
    <DefaultSettings>
      <SourceLocation DefaultValue="~remoteAppUrl/Pages/HelloWorld.html" />
      <RequestedWidth>200</RequestedWidth>
      <RequestedHeight>200</RequestedHeight>
    </DefaultSettings>
    
  4. Remove the "Presentation", "Project", and "Document"Capability elements from the Capabilities element, so that only the "Workbook" Capability element remains.
    <Capabilities>
      <Capability Name="Workbook" />
    </Capabilities>
    
  5. Save these changes to the HelloWorld.xml file.

To change the Start Action property in the Debugging property page of the project

  1. In Solution Explorer, choose the project name (HelloWorld).
    The Project Properties property page for the project appears in the pane below the Solution Explorer.
  2. Under App, in the Start Action list, choose Microsoft Excel.

To debug the app in Excel

  1. On the menu bar, choose Debug, Start Debugging.
    Excel 2013 opens with the HelloWorld app running as a content app in the worksheet.
  2. Click the Write Data, Read Selected Data, Bind Selected Data, Read Bound Data, and Add Event buttons to perform the same actions as before.
    Figure 10. Debugging as a content app

    Debugging as a content app
And here, your first task using Visual Basic...
This article demonstrated how to create a Hello World task pane app for Excel, and then add some UI and JavaScript to read, write, and bind to data in the worksheet. We also added a simple event handler to the binding to re-read its data whenever it is changed. We then changed the Start Action to run the same code as a task pane app in Word. Finally, we modified the manifest to run the app as a content app in an Excel worksheet.
To learn more about developing apps for Office, see the following sections of the documentation.


If IE loads when you start and attempts to access a URL like this when you start the app: "osf://apps/OSF_HostAppPresenceMutexName{F559498D-AE1C-40ED-9987-19F5A6485665}" then enable protected mode for the internet zone in internet explorer

By default HelloWorld.js is actually called Home.js and is located in solution>project>app>home

The various javascript methods that you are asked to add should be added as root functions in home.js, they should not be contained within any of the default code

There is no 'app' menu as referenced in the first section of changing the project to word.

Credit:       http://msdn.microsoft.com/en-us/library/office/fp142161.aspx 

 

No comments:

Post a Comment