Creating Calculator Office Apps using Visual Studio 2012

In this article we are explaining how to create a calculator separately in Office Apps and we can make it in ExcelSheet as well as in Microsoft Word 2013. It depends on your choice. In this article we will make the natural calculator that will perform the calculation on the numbers in a natural way. It will perform +, - , * and / .

Let's have a look at the following steps:

  1. First start Visual Studio 2012 RC.
       
  2. Now click on the File menu and choose New Project.

  3. A New Project Dialog box opens like this:

    cal1.jpg

  4. In this just expand the Visual C# and under it just expand the Office/SharePoint:

    cal2.jpg

  5. Now select the Apps option from it and select the App for Office 2013 in the center pane as given below:

    calc1234.jpg

  6. Give the name to the application and click on OK button.

    calc3.jpg

  7. The Create App for office dialog box will display. In it by default the Task Pane app option is selected and now just click on the Finish button:

    calc4.jpg

  8. Now Visual Studio creates the project and it will display in the Solution Explorer like this:

    calc5.jpg

  9. Now just develop the application and to design the appearance of the app we will add the following HTML code in the default page of the project
    and to do this just remove the default HTML code under the body tag and replace it with the following code as shown below:

    <!DOCTYPE html>

    <
    html>
     
    <head>
       
    <meta charset="UTF-8" />
       
    <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
       
    <title>calculator</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/calculator.js"></script>
     
    </head>
     
    <body>
       
    <h1>Calculator</h1>
       
    <div id="SectionContent">
             
    <div id="result" class="result">
                 
    <span id="storeddata" style="font-size:medium"></span><br />
                 
    <span id="inserteddata">0</span>
             
    </div>
             
    <hr />
             
    <br />
             
    <div id="buttons" style="text-align:center;">
                 
    <!-- First row of buttons: C/EC, MSR, M-, M+ -->
                 
    <input id="cleardata" type="button" class="button" value="CE" onclick="clearDatas()"/>
                 
    <input id="memory"  type="button" class="button" value="MSR" />
                 
    <input id="memoryminus"  type="button" class="button" value="M-" />
                 
    <input id="memoryplus"  type="button" class="button" value="M+" />
                 
    <br />
                 
    <!-- Second row of buttons: 7, 8, 9, '/' -->
                 
    <input id="7"  type="button" class="button" value="7" onclick="EnterNumber(this)"/>
                 
    <input id="8"  type="button" class="button" value="8" onclick="EnterNumber(this)"/>
                 
    <input id="9"  type="button" class="button" value="9" onclick="EnterNumber(this)"/>
                 
    <input id="divide"  type="button" class="button" value="/" onclick="includeOperator(this)"/>
                 
    <br />
                 
    <!-- Third row of buttons: 4, 5, 6, '*' -->
                 
    <input id="4"  type="button" class="button" value="4" onclick="EnterNumber(this)"/>
                 
    <input id="5"  type="button" class="button" value="5" onclick="EnterNumber(this)"/>
                 
    <input id="6"  type="button" class="button" value="6" onclick="EnterNumber(this)"/>
                 
    <input id="multiply"  type="button" class="button" value="*" onclick="includeOperator(this)"/>
                 
    <br />
                 
    <!-- Fourth row of buttons: 1, 2, 3, '-' -->
                 
    <input id="1"  type="button" class="button" value="1" onclick="EnterNumber(this)"/>
                 
    <input id="2"  type="button" class="button" value="2" onclick="EnterNumber(this)"/>
                 
    <input id="3"  type="button" class="button" value="3" onclick="EnterNumber(this)"/>
                 
    <input id="minus"  type="button" class="button" value="-" onclick="includeOperator(this)"/>
                 
    <br />
                 
    <!-- Fifth row of buttons: 0, '.', '+', '=' -->
                 
    <input id="0"  type="button" class="button" value="0" onclick="EnterNumber(this)"/>
                 
    <input id="decimal"  type="button" class="button" value="." onclick="EnterNumber(this)"/>
                 
    <input id="plus"  type="button" class="button" value="+" onclick="includeOperator(this)"/>
                 
    <input id="equals"  type="button" class="button" value="=" onclick="evaluate();"/>
             
    </div>
             
    <hr />
             
    <br />
           
    <div id="buttonsofcontent" style="text-align:center"></div>
       
    </div>
     
    </body>
    </
    html>


  10. Now to handle the events of all the buttons appearing in the calculator we will write some functions for it and to to this just expand the Scripts
    option in the Solution Explorer as shown below:

    cacl111.jpg


  11. Now under the Office folder just open the calculator.js to show the default JavaScript file for the application as shown below:

    calc122.jpg

  12. Now add the following functions to calculator.js like this:

    var result;
    var
    savedData;
    var
    insertedData;
    var
    savedOperation = [];

    Office.initialize =
    function (reason) {
       
    // Use the following API wherever you want access to the Office document object.
       
    // Office.context.document;

       
    // Check if setSelectedData method is supported and include sample content to insert data. 
     
      
    if (Office.context.document.setSelectedDataAsync) {
           
    var setDataDiv = "<input type='button' style='width:47%;margin:2px;' onclick='setData()' value='Insert Data' />";
           
    document.getElementById(
    "buttonsofcontent").innerHTML += setDataDiv;
     
      }

       
    // Check if getSelectedData method is supported and include sample content to get data. 
       
    if (Office.context.document.getSelectedDataAsync) {
           
    var getDataDiv = "<input type='button' style='width:47%;margin:2px;' onclick='getData()' value='Get Data'/>";
           
    document.getElementById(
    "buttonsofcontent").innerHTML += getDataDiv;
       
    }

       
    // Capture a reference to the output div onload.
       
    result = document.getElementById(
    'result');
       
    savedData = document.getElementById(
    'storeddata');
       
    insertedData = document.getElementById(
    'inserteddata');
       
    savedOperation[0] =
    "undefined";
       
    savedOperation[1] =
    "undefined";
    }

    // Add numbers to the number display.

    function
    EnterNumber(node) {

       
    var newEntry = node.value;
       
    var dataEntry = insertedData.innerHTML;
       
    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 (insertedData.innerHTML == "0") {
           
    insertedData.innerHTML = newEntry;
       
    }
       
    else {
           
    insertedData.innerHTML += newEntry;
       
    }
    }

    // Convert the information in the display to a number

    // and store both operand and operator.

    function
    includeOperator(node) {

       
    if (savedOperation[1] == "undefined") {

           
    // Parse the value and operator for the operation.
           
    var operator = node.id;
           
    var operand = insertedData.innerHTML;
           
    var operation;

           
    operand = parseFloat(operand);

           
    // Store the operation as an anonymous function
           
    // in the global variable storedOperation.
           
    switch (operator) {
               
    case "divide":
                   
    operation =
    function (a, b) { return a / b };
                   
    savedData.innerHTML = operand +
    " / ";
                   
    break;

               
    case "multiply":
                   
    operation =
    function (a, b) { return a * b };
                   
    savedData.innerHTML = operand +
    " * ";
                   
    break;

               
    case "minus":
                   
    operation =
    function (a, b) { return a - b };
                   
    savedData.innerHTML = operand +
    " - ";
                   
    break;

               
    case "plus":
                   
    operation =
    function (a, b) { return a + b };
                   
    savedData.innerHTML = operand +
    " + ";
                   
    break;
           
    }

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

    // Removes all entries from the output and sets the value to '0'.

    function
    clearEntries() {
       
    insertedData.innerHTML =
    "0";
       
    storedData.innerHTML =
    "";
    }

    // 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 (savedOperation[0] != "undefined") {

           
    // Define the two operands and operation to perform.
           
    var x = savedOperation[0];
           
    var y = insertedData.innerHTML;
           
    y = parseFloat(y);
           
    var operation = savedOperation[1];
           
    var result;

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

           
    // Display results and clear the stored data span.
         
      insertedData.innerHTML = result;
           
    savedData.innerHTML =
    "";
           
    // Clear the data out of the storedOperation array.
           
    savedOperation[0] =
    "undefined";
           
    savedOperation[1] =
    "undefined";
       
    }
    }

    // JavaScript has some issues with evaluating floating point
    // decimal numbers, so they need to be evaluated differently.

    function
    evaluateFloat(x, y, operation) {

       
    var stringX = String(x);
       
    var stringY = String(y);
       
    var decimalPlace = 0;
       
    var result;

       
    // Determine the level of precision needed for the float operation.
       
    // Check the x variable to see if it is the float.
       
    if (stringX.indexOf(".") > -1) {
           
    decimalPlace = (stringX.length - stringX.indexOf(
    ".")) - 1;
       
    }

       
    // Check to see if the y variable is the float, and if so,
       
    // if it has more decimal places.
       
    if (stringY.indexOf(".") > -1) {
           
    if (decimalPlace < ((stringY.length - stringY.indexOf(".")) - 1)) {
               
    decimalPlace = (stringY.length - stringY.indexOf(
    ".")) - 1;
           
    }
       
    }

       
    // Transform the numbers into integers by multiplying them
       
    // by 10 to a power equal to the number of decimal places.
       
    result = operation((x * Math.pow(10, decimalPlace)), (y * Math.pow(10, decimalPlace)));
       
    result = Math.round(result) / Math.pow(10, decimalPlace);

       
    return result;
    }

    // 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 = insertedData.innerHTML;

       
    // Set the selected data into the document as text.
       
    Office.context.document.setSelectedDataAsync(
           
    value,
    function () { });
    }

    // Gets data from the current document and returns it as a number.

    function
    getData() {

       
    var dataValue = 0;

       
    // Get the current selection from the Word document.
       
    Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
           
    function (result) {
          
        
    if (result.status != "failed") {
                   
    var results = result.value;
                   
    results = parseFloat(results);

                   
    if (!isNaN(results)) {
                       
    dataValue = results;
                   
    }
               
    }
               
    insertedData.innerHTML = dataValue;
           
    });

    }

  13. Now if we want to see the output in the Word document then just click on the name of the application and under the properties window just see
    the Start Action property, as in:

    calc6.jpg


  14. From the Dropdownlist we will choose the Microsoft Word option.

    calc7.jpg

  15. Now to run the application just press the F5 key or under the Debug menu just click on start debugging like this:

    calc8.jpg

  16. The output window will look like this:

    calc9.jpg

  17. In this if we will click on any number digit and click on +, -, *, / then it will perform the operation on the digits accordingly.

    calc10.jpg

    calc11.jpg

 

Up Next
    Ebook Download
    View all
    Learn
    View all