NAV
shell apex java php C#

Introduction

Glossary

General

Admin

Computation Management

Requests

Implemented Excel Functions

The formulae accepted by CalcFusion are listed below. This list constantly evolves so keep posted of our updated through our Twitter account. Also, CalcFusion cannot/execute Macro’s, Xll and other Excel Add-On. While you are uploading your Excel file, CalcFusion will check if all elements are readable and can be executed.

Date and Time functions

Engineering Functions

Financial Functions

Logical Functions

Information Functions

Text Functions

Performance

The time it takes for CalcFusion to execute your computation is dependent on different factors.

One important factor is the volume of your computation in terms of spreadsheet file size and the percentage of formula and data it contains, as well as the number of In Data (parameters) and Out Data (results).

Having in mind the primary purpose of the CalcFusion which is to compute, we recommend that you keep your file size to about 64Kb.

To put the size in perspective, the size of a professionally-made financial model can range from 30 KB to 300 KB. These spreadsheets contain computations (formulae and logic) and some parameter or reference tables.

Furthermore, the principle of connecting CalcFusion to your IT Systems is for you to keep your data in a database instead of exporting it to your spreadsheet. This is not only to obtain the best possible computation performance results, but more importantly it is also the best practice for keeping the integrity of your data. Can the files be bigger? Technically, yes. However, this is the standard size that we recommend. We could adapt a custom server setup for you if you have specific requirements to manage.

To give you an idea from our own speed test:

Spreadsheet Size Number of cells Data / Formula ratio Server Compute Time Round trip time
64KB 4,000+ 12% / 88% 376ms 449 ms
64KB 8,000+ 94% / 6% 127ms 173ms
128KB 11,000+ 5% / 95% 560ms 629ms
128KB 21,000+ 87% / 13% 272ms 326ms
256KB 25,000+ 2% / 98% 930ms 970ms
256KB 46,000+ 83% / 17% 516ms 561ms

Test Case

Overall, CalcFusion is a computation engine, not a data store.

By using CalcFusion’s Audit function, you can test your own spreadsheet to get some information on its performance time, percent of data to formula, and also check for errors and warnings.

User Guide

General

Introduction

What is CalcFusion?

Calcfusion is a computation engine that communicates with other IT systems / client applications through Web Services.

It receives variables from the IT System which are used in the computations, and then returns computed results.

The formulae, logic, and some local data are set on Excel spreadsheets that are uploaded on CalcFusion console.

How it Works

CalcFusion is a cloud based service that allows the integration of Excel computations into IT systems.

With CalcFusion, your IT department will have to create interfaces or modify your system’s existing interface to contain the functions or modules that are to be integrated. The CalcFusion console is where Excel spreadsheets that contain the computations are uploaded by your End-Users.

Through web services, CalcFusion receives parameters, executes computations requested by the IT System on Excel, and returns the result(s).

CalcFusion is a controlled environment that lets organizations manage their Excel versions, give rights to users, store computation archives, test and audit Excel files, and more.

Alt text

Computation Implementation Flow

Business Managers need to create an Excel Spreadsheet (or use an existing file) that will contain the formulae, logic, and local data.

They need to establish a dedicated tab (“In” tab) where the variables sent by the IT System will be located.

Another dedicated tab (“Out” tab), should be established containing all the data/information that CalcFusion will return to the IT System.

The Business Manager can the use as many tabs as they need to create their computation. These tabs usually contain formulae and some local Excel data.

IT Managers need to manage the communication between the IT System and CalcFusion through Web Services.

Libraries are provided to help them setup these interactions. The implementation consists of:

Once the Excel file and the web services have been setup, the spreadsheet needs to be uploaded, tested and activated on the CalcFusion console.

Other Functionalities

Console

Computation Screen / Landing Page

The Computation Screen is also the landing page of the CalcFusion Console right after you sign-in.

The list will be empty upon creation of your organization’s account. It will be populated once you start creating your Computations, and when Computation(s) are shared to you by other users.

Alt text

The Menu and Header are elements that will be visible on all the screens of the CalcFusion Console.

Clickable elements specific to the Computation Screen are:

Logs

Accessible from Computation Screen > Computation Icon > Logs

This screen contains a log of all the request made for the selected Computation.

This is also where you can download the Archive of the Computation requests.

Alt text

Computation Folder

Accessible from Computation Screen > Computation Name.

Clicking on a Name of a Computation (Example: Template – Commission) will open a new screen containing the Excel spreadsheets which has been uploaded by you or your users.

Alt text

Clickable elements specific to the Computation Folder are:

Audit

Accessible from Computation Screen > Computation Name > Excel Icon > Audit

This screen is where you can check if your spreadsheet contains errors.

Alt text

Compare

Accessible from Computation Screen > Computation Name > Excel Icon > Compare

This screen is where you can check the modifications made between two spreadsheets.

Click the download icon to download the compare result.

Alt text

Dashboard

The Dashboard contains information regarding your usage of CalcFusion.

This is where you can check how many requests you have called and how much space you are consuming, compared to the limits of your subscription plan.

Alt text

Account

The account screen contains the following tabs to manage your organization’s CalcFusion Account.

Alt text

Alt text

Installation & Setup

Salesforce

Prerequisites

Below are the requirements for using CalcFusion in Salesforce:

Install the Core API Library Package

Alt text

Alt text

Alt text

Alt text

Setup

Once CalcFusion has been installed, you need to setup your CalcFusion settings.

Alt text

Alt text

Alt text

Alt text

Alt text

You are now ready to use CalcFusion from within Salesforce.

WordPress

Prerequisites

In order to use the CalcFusion Plugin for WordPress, your PHP project should be configured accordingly:

Plugin Installation

There are 3 ways you can install the CalcFusion for WP plugin, each section below provides a step-by-step guide for each method.

Automatic using WordPress Admin

Manual using WordPress Admin

This method can be used if you have already downloaded the CalcFusion Plugin in .zip format.

Manual using FTP

This method requires FTP familiarity and can be used if you have already downloaded the CalcFusion Plugin in .zip format.

CalcFusion Setup Page

Once the plugin has been installed, you need to setup your CalcFusion parameters.

Uninstalling the Plugin

Java

Prerequisites

In order to use the Core API Java SDK, your Java project should be configured accordingly:

Install Core API SDK

Download the Core API for Java SDK, and include the Core API libraries (.jar file) in your Java System project and import the packages/classes.

PHP

Prerequisites

In order to use the CalcFusion Plugin for WordPress, your PHP project should be configured accordingly:

Install Core API SDK

<?php
require_once "calcfusion-api-1.0.2.phar";
?>

Download the Core API for PHP SDK, and include the Core API library (.phar file) into your PHP file.

C Sharp

Prerequisites

In order to use the Core API .Net SDK, your Java project should be configured accordingly:

Install Core API SDK

Download the Core .Net API (CalcFusionClient.dll file) and add it as reference in your .Net System project.

Downloads

Java

Download CalcFusion Core API

The Java CalcFusion Core API SDK can be downloaded here.

File Dependencies

Aside from the Core API libraries, you would need to import the following libraries:

PHP

Download CalcFusion Core API

The PHP CalcFusion Core API SDK can be downloaded here.

Extensions Needed

See Php Prerequisites for more details.

C Sharp

Download CalcFusion Core API

The C# CalcFusion Core API SDK can be downloaded here.

File Dependencies

Aside from the Core API assembly, you need to install the following assemblies in your bin folder:

Assemblies NuGet Packages
Newtonsoft.Json.dll Json.NET version 6.0.8
RestSharp.dll RestSharp version 105.0.1

Wordpress

Download CalcFusion Wordpress Plugin

Download CalcFusion Plugin for WordPress here.

Extensions Needed

Salesforce

Install the CalcFusion client

Install to be done through the App Exchange here

Developer Guide

Overview

CalcFusion API provides a way for developers to integrate CalcFusion functionality. There are 2 kinds of APIs available from CalcFusion – the Core API and REST API:

Core API

The Core API provides low-level calls to access CalcFusion functionality. By instantiating a Core API object, a REST API call can be made thru that object to perform CalcFusion computation tasks. The main task of the Core API is to provide an interface for your IT System’s authentication and authorization, and for sending web service requests.

REST API

The REST API provides a set of language-independent RESTful Web Services. Each REST API corresponds to a specific CalcFusion action (such as Computation Execution).

Salesforce

Intro

The Core API inside the CalcFusion for Salesforce package containts the following classes that allow for synchronous REST API calls:

Implementation Flow

CalcFusion provides a way to use Excel spreadsheets to manage computations and return results to Salesforce. The diagram below describes the general steps on how CalcFusion can be integrated:

Alt text

Step 1: Setup Credentials

The Core API uses the OAuth 2.0 protocol for authentication and authorization. Whenever Salesforce needs to access a CalcFusion REST API, it needs to send the API request over a valid Core API access token. In general, the authentication process is:

Step 2: Use the Core API to call a REST API

In general, the process of calling a REST API is:

Step 3: Error Handling

After CalcFusion processes a request, it returns the requested data. If the request has encountered an error, CalcFusion returns an error message as part of the response.

Core Library

The CalcFusionClient Class

When Salesforce sends a REST API request (for example, a “compute” request), the CalcFusionClient class uses the credentials defined in the CalcFusion Setup tab to send an authorization request to CalcFusion. Once authorized, an access token is returned which the CalcFusionClient class will use to process the REST API request and all succeeding requests.

These are the methods available in this class:

requestService(servicePath, method, parameters)

The requestService method manages all web service requests from an IT System. It works by creating a HTTP request for a RESTful web service request.

The servicePath refers to the URL path that will handle the web service request (including the web service path parameters).

The method refers to the HTTP request method to use (GET/POST).

The parameters refers to the HTTP parameters required by the servicePath in key-value pair form (see Notes below).

After processing the request, it will return data in String format (formatted in JSON). An error message will be returned if an error has occurred.

The requestService method pass an additional HTTP parameter called “cfxlContextInfo” to the web service. The cfxlContextInfo contains Core API Library information such as Context and Version.

getDataValue(requestResult, propertyName, outputParameter)
string result = "";
string returnValue = "";

//Make the Compute Web Service Call
result = cfClient.requestService("compute/10002", "GET", paramsMap);

//Get data from "Out!B5"
returnValue = cfClient.getDataValue(result, "data", "Out!B5");

The getDataValue method provides a way to easily extract specific data from a web service response.

The requestResult refers to the response data (in JSON String format) returned by a requestService method call.

The propertyName refers to the property in the response data from which to get the desired data.

The outputParameter refers to the item within the specified property from which to get the desired data. For the ‘data’ property, it is the spreadsheet tab/cell (defined as an output parameter in a requestService method call) from which to get the desired value.

The getDataValue returns the value associated with the specified outputParameter.

buildErrorComputeReturn(errorMessage, status, errorCode)
string result = "";

//Make the Compute Web Service Call
result = cfClient.requestService("compute/10002", "GET", paramsMap);
CalcFusion.CalcFusionClient.RestCallValues RestCallValuesDeserialized;

try{
     RestCallValuesDeserialized = (CalcFusion.CalcFusionClient.RestCallValues)JSON.deserialize(result,CalcFusion.CalcFusionClient.RestCallValues.class);
}catch(exception e){
     RestCallValuesDeserialized = cfClient.buildErrorComputeReturn("Unable to parse JSON response.", "FAILED", "9999");
}

return RestCallValuesDeserialized;

The buildErrorComputeReturn method returns an error object of type CalcFusion.CalcFusionClient.RestCallValues.

The errorMessage refers to the Error Message that should be saved in the error object.

The status refers to the Status that should be saved in the error object.

The errorCode refers to the Error Code that should be saved in the error object.

When CalcFusion encounters an error during a web service request, it will return the details of the error as part of the response and can be deserialized into a CalcFusion.CalcFusionClient.RestCallValues object. To clear all data in the CalcFusion.CalcFusionClient.RestCallValues object and only keep error information (or to customize error codes and messages), issue a buildErrorComputeReturn method call.




SetCustomSettingValues(configName)
string result = "";

// Do not save the custom settings before the API call is complete
cfClient.doSaveOfCustomSettings = false;

//Make the Compute Web Service Call
result = cfClient.requestService("compute/10002", "GET", paramsMap);

cfClient.SetCustomSettingValues("Config1");

The SetCustomSettingValues method is used for saving CalcFusion credentials and other details into a custom setting.

The configName refers to the name of the custom setting.




These are the inner classes available in this class:

CalcFusion.CalcFusionClient.RestCallValues
string result = "";

//Make the Compute Web Service Call
result = cfClient.requestService("compute/10002", "GET", paramsMap);

CalcFusion.CalcFusionClient.RestCallValues RestCallValuesDeserialized;
RestCallValuesDeserialized = (CalcFusion.CalcFusionClient.RestCallValues)JSON.deserialize(result, CalcFusion.CalcFusionClient.RestCallValues.class);

This class provides a structure consistent with the properties of a web service response.

Property Name Type
cfxlContextInfo String
cfxlCustom String
data List
requestId String
response CalcFusion.CalcFusionClient.responseClass

To deserialize the JSON response data from a requestService method call into a CalcFusion.CalcFusionClient.RestCallValues object, issue a JSON.deserialize call.

CalcFusion.CalcFusionClient.responseClass
string result = "";

//Make the Compute Web Service Call
result = cfClient.requestService("compute/10002", "GET", paramsMap);

CalcFusion.CalcFusionClient.RestCallValues RestCallValuesDeserialized;
RestCallValuesDeserialized = (CalcFusion.CalcFusionClient.RestCallValues)JSON.deserialize(result, CalcFusion.CalcFusionClient.RestCallValues.class);

//Get results of the CalcFusion Web Service call
if(RestCallValuesDeserialized.response.status == "OK"{
     if(RestCallValuesDeserialized.data <> null{
          //Some code here
     }
}else {
     return RestCallValuesDeserialized.response.errorMessage;
}

This class provides a structure consistent with the attributes of the ‘response’ property of a web service response.

Property Name Type
errorCode String
errorMessage String
status String

It is useful for checking response status and error messages.









The CalcFusionHlprTest Class

The CalcFusionHlprTest class is a helper class that is used by test classes in the Calcfusion for Salesforce package to produce test data. It can also be used for building your own test classes.

These are the methods available in this class:

createConfigData()

The createConfigData method creates an instance of the CalcFusion custom setting to be used with the test classes.

createConfigDataNoAccessToken()
@isTest
private class ComputeControllerTest {
    static testMethod void CalcFusionControllerTest(){
        CalcFusion.CalcFusionHlprTest.createConfigData();
        ComputeController cfc = new ComputeController();
        Opportunity o = createOpp();

        cfc.CallCalcFusion();
        cfc.DoCalcfusionWork(o.ID);
    }

    static testMethod void CalcFusionControllerComputeCommissionTest(){
        CalcFusion.CalcFusionHlprTest.createConfigData();
        ComputeController cfc = new ComputeController();

        string retVal;

        //Test the ComputeCommission call with a null value
        retVal = cfc.ComputeCommission(null, "OppType");
        //Test the ComputeCommission call with a valid value
        retVal = cfc.ComputeCommission(2500, "OppType");

        system.assertNotEquals(retVal, null);
    }

    static testMethod void CalcfusionControllerComputeCommissionNoTokenTest(){
        CalcFusion.CalcFusionHlprTest.createConfigDataNoAccessToken();
        ComputeController cfc = new ComputeController();
        cfc.callFailedTest = true;

        string retVal;
        retVal = cfc.ComputeCommission(2500, "OppType");

        system.assertNotEquals(retVal, null);
    }

/**
* Create an Opportunity that can be used by the test methods
* @return Opportunity object
*/
static Opportunity createOpp(){
    Opportunity o = new Opportunity();
    o.Name = "Opp Test";
    o.StageName = "Open";
    o.CloseDate = date.Today();
    o.Amount = 1000;
    o.Type = "OppTypeTest";

    insert o;
    return o;
    }
}

The createConfigDataNoAccessToken method creates an instance of the CalcFusion custom setting with no access token, to be used with the test classes.

















































Sample Implementation

Sample Scenario

From the Salesforce Opportunity Detail screen, use the Amount and Type to compute for the Commission Amount and Remarks from a spreadsheet using CalcFusion, then display the result. For this, you need to do the following steps:

Implementation

Sample Spreadsheet:

For the sample scenario, suppose you have a spreadsheet containing the following tabs (In, Out, Amount Range Tabs) that has been uploaded to CalcFusion:

Tab / Cell Description
IN Tab The IN Tab where you define the input parameters, in this case the Amount and Type
B1 Amount from which the Commission will be computed against
B2 Type from which the Commission will be computed against
Out Tab The OUT Tab where you get the output values, in this case the Commission Amount and Remarks
B5 The Commission Amount that we need to get using the “compute” web service
B6 The Remarks that we need to get using the “compute” web service
Other tabs Other tabs for defining the formulae for computing the Commission Amount (in this case, it’s the Amount Range tab)
Step 1: Modify the Opportunity Detail Screen

Alt text

Alt text

Property Name Value
Data Type Text
Field Label Commission (or Remarks)
Length 255
Field Name Commission (or Remarks)
Other fields Take default values
Establish Field-level Security Take default values
Add to Page Layouts Take default values

Alt text

Property Name Value
Label Compute Commission
Name Compute_Commission
Display Type Detail Page Button
Behavior Display in existing window without sidebar or header
Content Source URL
Button or Link URL /apex/ComputePage?ID={!Opportunity.Id}
Link Encoding Unicode (UTF-8)

Alt text

Alt text

Alt text

Step 2: Create an Apex Class

Alt text

///Get the ID of the Opportunity so that we can update it and return to it
string oppID = "";
oppID = System.currentPageReference().getParameters().get("ID");

//Retrieve Opportunity to be computed
list oppList = new list();
oppList = [Select ID, Amount, Type
               From Opportunity
               Where ID = : oppID];
system.debug("In DoCalcfusionWork");
if(oppList.size() == 0){
     return;
}

//Get the Opportunity Amount
decimal oppAmount = oppList[0].Amount;

//Get the Opportunity Type
string oppType = oppList[0].Type;




















//Setup parameters for the Web Service Call
map<string, string> paramsMap = new map<string, string>();
paramsMap.put("cfxlArchive", "false");

//Define the input parameters and pass the Amount and Type as parameter values
paramsMap.put("In!B1", "[\"IN\",\"" + string.valueOf(oppAmount) + "\"]");
paramsMap.put("In!B2", "[\"IN\",\"" + oppType + "\"]");

//Get data from the specified Out Tabs and Cells
paramsMap.put("Out!B5", "[\"OUT\"]");
paramsMap.put("Out!B6", "[\"OUT\"]");













CalcFusion.CalcfusionClient cfClient = new CalcFusion.CalcfusionClient();




string result = "";
result = cfClient.requestService("compute/10002", "GET", paramsMap);


//Save the Access Token to the custom setting
cfClient.doSaveOfCustomSettings = true;
cfClient.SetCustomSettingValues("Config1");

//Variables for storing the results
string returnValue = "";
decimal returnDecimal;
string newCommission = "";
string remarksValue = "";

//Get results of the CalcFusion Web Service Call
CalcFusion.CalcFusionClient.RestCallValues RestCallValuesDeserialized;
RestCallValuesDeserialized = (CalcFusion.CalcFusionClient.RestCallValues)JSON.deserialize(result, CalcFusion.CalcFusionClient.RestCallValues.class);

if(RestCallValuesDeserialized.response.status == "OK"){
     if(RestCallValuesDeserialized.data <> null){

          //Get data from "Out!B5"
          returnValue = cfClient.getDataValue(result, "data", "Out!B5");
          returnDecimal = decimal.valueOf(returnValue);
          newCommission = returnDecimal.toPlainString();

          //Get data from "Out!B6"
          remarksValue = cfClient.getDataValue(result, "data", "Out!B6");
     }
}






























/**
* Controller Class that is used by the ComputePage.page.
* This class will help call CalcFusion to compute the Commission__c
* and Remarks__c custom fields on the Opportunity Page
* based on the Amount and Type standard fields.
*
*/

public with sharing class ComputeController {

     // callFailedTest is used for unit testing
     public boolean callFailedTest{get;set;}
     private string opportunityID = "";
     private string remarksValue = "";
     private string jsonFromRESTCall = "";

     public ComputeController(){
          callFailedTest = false;
     }

     public ComputeController(ApexPages.StandardController stdController){
          callFailedTest = false;
          opportunityID = stdController.getId();
     }

     /**
     * Method called by the Visualforce Page, which will do the work to call CalcFusion
     *
     * @return PageReference back to the Opportunity
     *
     */
     public PageReference CallCalcFusion(){
          //Get the ID of the Opportunity so that we can update it and return to it
          string oppID = "";
          if(string.isBlank(opportunityID)){
               oppID = System.currentPageReference().getParameters().get("ID");
          }else{
               oppID = opportunityID;
          }

          //If we do not have an Opportunity ID, then this page was called in error
          if(string.isBlank(oppID)){
               return null;
          }

          //Call CalcFusion and update the Opportunity
          DoCalcfusionWork(oppID);

          //Return to the Opportunity
          return new PageReference("/" + oppID);
     }

     /**
     * Method to retrieve the current oppAmount and oppType, call CalcFusion and
     * update the Commission__c and Remarks__c custom fields
     *
     * @param opportunityID
     * Opportunity ID to be computed
     *
     * @return void
     *
     */
     @TestVisible
     private void DoCalcfusionWork(string opportunityID){
          //Retrieve Opportunity to be computed
          list oppList = new list();
          oppList = [Select ID, Amount, Type
               From Opportunity
               Where ID = :opportunityID];
          system.debug("In DoCalcfusionWork");
          if(oppList.size() == 0){
               return;
          }

          //Get the Opportunity Amount
          decimal oppAmount = oppList[0].Amount;

          //Get the Opportunity Type
          string oppType = oppList[0].Type;

          //Call the method to compute the commission and get the Remarks
          string newCommission = "";
          newCommission = ComputeCommission(oppAmount, oppType);

          //Update the Opportunity with the new Commission Amount and Remarks
          oppList = database.query("Select ID, Remarks__c, Type, Commission__c" +
               " From Opportunity" +
               " Where ID = :opportunityID");
          oppList[0].put("Commission__c", newCommission);
          oppList[0].put("Remarks__c", remarksValue);

          update oppList[0];

     }

     /**
     * Make the ComputeCommission call
     *
     * @param amount oppAmount
     * Decimal value of amount to compute
     * @param oppType
     * String value of type to compute
     * @return {@code String} The computed result
     */

     public string ComputeCommission (decimal oppAmount, string oppType){
          //Protect the Parameters
          if(oppAmount == null){
               return "";
          }

          string outParamCommission = "Out!B5";
          string outParamRemarks = "Out!B6";

          //Setup CalcFusion Client API class
          CalcFusion.CalcFusionClient cfClient = new CalcFusion.CalcFusionClient();

          // Do not save the custom settings before the API call is complete
          cfClient.doSaveOfCustomSettings = false;

          //Make CalcFusion Web Service call
          CalcFusion.CalcFusionClient.RestCallValues RestCallValuesDeserialized =
               MakeComputeRESTCall(oppAmount, oppType, outParamCommission, outParamRemarks, cfClient);

          //Save the Access Token to the custom setting
          cfClient.doSaveOfCustomSettings = true;
          cfClient.SetCustomSettingValues("Config1");

          //Get results of the CalcFusion Web Service Call
          if(RestCallValuesDeserialized.response.status == "OK"){
               if(RestCallValuesDeserialized.data <> null){
                    decimal returnDecimal;
                    string returnValue = "";
                    //Get data from "Out!B5"
                    returnValue = cfClient.getDataValue(jsonFromRESTCall, "data", outParamCommission);

                    try{
                         returnDecimal = decimal.valueOf(returnValue);
                    }catch(exception e){
                         returnDecimal = -1;
                    }
                    //Get data from "Out!B6"
                    remarksValue = cfClient.getDataValue(jsonFromRESTCall, "data", outParamRemarks);
                    return returnDecimal.toPlainString();
               }else{
                    return "Data Return Value is Null";
               }
          }else{
               return RestCallValuesDeserialized.response.status;
          }

     }

     /**
     * Make the actual CalcFusion Web Service call and return results
     *
     * @param oppAmount
     * Amount field from the Opportunity
     * @param oppType
     * Type field from the Opportunity
     * @param outParamCommission
     * Commission to be computed from Excel
     * @param outParamRemarks
     * Remarks to be retrieved from Excel
     * @param CalcFusion.CalcfusionClient cfClient
     * CalcFusion API class
     *
     * @return CalcFusion.CalcfusionClient.RestCallValues – Results from Web Service Call
     *
     */
     public CalcFusion.CalcFusionClient.RestCallValues MakeComputeRESTCall(decimal oppAmount, string oppType, string outParamCommission, string outParamRemarks, CalcFusion.CalcFusionClient cfClient){

          //Initialize Variables
          jsonFromRESTCall = "";

          //Setup parameters for the Web Service Call
          map<string, string> queryStringParamsMap = new map<string, string>();
          queryStringParamsMap.put("cfxlArchive", "false");

          //Define the input parameter and pass the Opportunity Amount and Type as parameter values
          queryStringParamsMap.put("In!B1", "[\"IN\",\"" + string.valueOf(oppAmount) + "\"]");
          queryStringParamsMap.put("In!B2", "[\"IN\",\"" + oppType + "\"]");

          //Get data from the specified Out Tabs and Cells
          queryStringParamsMap.put(outParamCommission, "[\"OUT\"]"); //"Out!B5"
          queryStringParamsMap.put(outParamRemarks, "[\"OUT\"]"); //"Out!B6"

          //Make the Compute Web Service Call
          jsonFromRESTCall = cfClient.requestService("compute/10002", "GET", queryStringParamsMap);

          CalcFusion.CalcFusionClient.RestCallValues RestCallValuesDeserialized;

          try{
               RestCallValuesDeserialized =
               (CalcFusion.CalcFusionClient.RestCallValues)JSON.deserialize(jsonFromRESTCall, CalcFusion.CalcFusionClient.RestCallValues.class);
          }catch(exception e){
               RestCallValuesDeserialized =                cfClient.buildErrorComputeReturn(CalcFusion.CalcFusionClient.RESPONSE_2009_MSG, "FAILED", string.ValueOf(CalcFusion.CalcFusionClient.RESPONSE_2009));
          }

          return RestCallValuesDeserialized;

          return null;
     }

}

































































































































































r>
























































Step 3: Create a Visualforce Page

Alt text

Property Name Value
Label ComputePage
Name ComputePage
Other fields Take default values
Visualforce Markup <apex:page controller=”ComputeController” action=”{!CallCalcFusion}”><apex:form ><apex:pageMessages />There has been an error processing the Calcfusion request. Please refer to the error above.</apex:form></apex:page>
Step 4: Manage User Profile for a Standard User

To allow a Standard User to perform computations using CalcFusion, you must grant access to the Visualforce page that calls a Controller that uses CalcFusion.

Alt text

Alt text

Alt text

Alt text

WordPress

Intro

There are 2 ways to send web service requests using the Core API – the Synchronous and Asynchronous API calls:

The Core API inside the “calcfusion-api-1.0.0.phar” contains the following classes that allow for asynchronus and synchronous REST API calls:

Core Library

The AsyncRequestThread Class

The AsyncRequestThread class is referenced by the methods of CalcFusionClient for executing asynchronous client request calls. The CalcFusionClient class already manages the processes needed for executing asynchronous requests, so there is no need to build your own code. The next section provides more details on how to make asynchronous requests.

The CalcFusionClient Class

The CalcFusionClient class provides the methods for sending CalcFusion credentials, obtaining access tokens and managing web service requests between an IT System and CalcFusion.

These are the methods available in this class:

$cfClient = new CalcFusionClient("https://api.calcfusion.com/CalcFusion-Core-WebServices/rest");
$accessToken = $cfClient -> Login($username, $password, $accountID, $appkey);

The login method initiates the OAuth 2.0 authentication process.

The refreshToken method provides a means to refresh an existing access token (by passing it as an array parameter). Alternately, you can refresh an existing access token by calling the “token/refresh” web service (see Notes below).

// Get the values of the Sales Amount and Product Type Incentive from the IT System
$salesAmount = 12000;
$productType = "TYPE03";

// Define the parameters and parameter values that you need to pass to the web service
$param = array();
$param.["cfxlArchive"] = "False";

// Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
$param["In!B1"] = "[\"IN\",\"".$salesAmount."\"]";
$param["In!B2"] = "[\"IN\",\"".$productType."\"]";

// Define that the output parameters will come from Out Tab Cells B5 and B6
$param["Out!B5"] = "[\"OUT\"]";
$param["Out!B6"] = "[\"OUT\"]";
$param["cfxlCustom"] = "This is a custom parameter.";

$result = $cfClient->requestService("compute/386", "GET", $param);

The requestService method manages all web service requests from an IT System. It works by creating a HTTP request for a RESTful web service request. The servicePath refers to the URL path that will handle the web service request (including the web service path parameters). The method refers to the HTTP request method to use (GET/POST). The parameters refers to the HTTP parameters required by the servicePath in key-value pair form (see Notes below). After processing the request, it will return data in String format (formatted in JSON). An error message will be returned if an error has occurred.













The logout method provides a means to invalidate an existing access token. Alternately, you can invalidate an existing access token by calling the “token/logout” web service (see Notes below).

//xAsynchronous web service calls using the same parameter values
$asyncRequestIdList = array();

for ($x=1; $x<10; $x++) {
 //Get the values of the Sales Amount and Product Type Incentive from the IT System
 $salesAmount = 12000;
 $productType = "TYPE03";

 //Define the parameters and parameter values that you need to pass to the web service
 $param = array();
 $param["cfxlArchive"] = "False";

 //Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
 $param["In!B1"] = "[\"IN\",\"".$salesAmount."\"]";
 $param["In!B2"] = "[\"IN\",\"".$productType."\"]";

 //Define that the output parameters will come from Out Tab Cells B5 and B6
 $param["Out!B5"] = "[\"OUT\"]";
 $param["Out!B6"] = "[\"OUT\"]";
 $param["cfxlCustom"] = "This is a custom parameter";

 //Use the asyncRequestService method to issue an asynchronous web service request and specify the request method and parameters
 $asyncRequestId = $cfClient->asyncRequestService("compute/386","GET",$param);

 //Put the Request Id in an Array List to be able to check the results later
 array_push($asyncRequestIdList, $asyncRequestId);
}

The asyncRequestService method manages all asynchronous web service requests from an IT System. It processes requests the same way as that of requestService, but it does not wait for a response before the next request is processed.



























The asyncCallbackResult method serves as a listener for the result of the asynchronous request. This is called by the AsyncRequestRunnable class when a response is already available. The result is stored in a resultStorage collection referenced by the provided asyncRequestId.

//Define the Array List for checking the results of each request
$resultStorage = array();

while(count($resultStorage) != count($asyncRequestIdList)) {
    for ($i=0; $i<count($asyncRequestIdList); $i++) {
        $asyncRequestId = $asyncRequestIdList[$i];

        //Check if there is already a result for a specific Request Id
        $requestResult = #cfClient->getAsyncRequestResult($asyncRequestId);

        //If no result yet, check the next Request Id
        if ($requestResult == null)
          continue;

        //If there is a result already, put it in the result list
        $ resultStorage[$asyncRequestId] = $requestResult;
    }
    //Implement a delay before restarting the checking (50 milliseconds)
    sleep(.5);
}

//Can now display the result or can be processed by going through the items inside asyncResultList
for ($j=0; $j<count($asyncRequestIdList); $j++) {
    $asyncRequestId = $asyncRequestIdList[$j];
    $requestResult = $resultStorage[$asyncRequestId];
    print_r($requestResult);
    print_r("");
}

unset($resultStorage);
unset($asyncRequestIdList);
unset($resultStorage);

The getAsyncRequestResult method is used to check and retrieve if the synchronous service request has already returned a result.































$libInfo = $cfClient->getContextInfo();

The getContextInfo() method below returns library information such as Context, Version and File Name in JSON format.

Notes:

Plugin Method

The plugin currently provides just one method:

<?php
require_once "calcfusion-api-1.0.0.phar";

// Get the values of the Sales Amount and Product Type Incentive from the IT System
$salesAmount = 12000;
$productType = "TYPE03";

// Define the parameters and parameter values that you need to pass to the web service
$param = array();
$param["cfxlArchive"]="False";

// Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
$param["In!B1"]="[\"IN\",\"".$salesAmount."\"]";
$param["In!B2"]="[\"IN\",\"".$productType."\"]";

// Define that the output parameters will come from Out Tab Cells B5 and B6
$param["Out!B5"]="[\"OUT\"]";
$param["Out!B6"]="[\"OUT\"]";
$param["cfxlCustom"]="This is a custom parameter.";

$result = wp_calcfusion_request_service("compute/386", "GET", $param);
?>

The wp_calcfusion_request_service method manages all authentication and web service requests from a WordPress page. It works by creating a HTTP request for a RESTful web service request.

The servicePath refers to the URL path that will handle the web service request (including the web service path parameters).

The method refers to the HTTP request method to use (GET/POST).

The parameters refers to the HTTP parameters required by the servicePath in key-value pair form (see Notes below).

Sample Implementation

Sample Scenario

Compute the Commission Amount from a spreadsheet using CalcFusion, then display the amount in your WordPress page.

For this, you need to do the following steps:

Implementation

Step 1: Setup Authentication (for Non-WordPress pages)

If the page you are using is a WordPress page, there is no need to setup authentication because the plugin automatically takes care of this.

However, if the page you are using is not a WordPress page (or is not inside the wp-content folder), you need to manually setup authentication to CalcFusion.

$cfClient=new CalcFusionClient("https://api.calcfusion.com/CalcFusion-Core-WebServices/rest");

To do this, create an instance of a CalcFusionClient class, passing the root URL of the CalcFusion web services:


$accessToken=$cfClient->login($username, $password, $accountID, $appkey);

Obtain an access token by sending your CalcFusion credentials – Email, Password (encrypted using SHA-1), Account ID and App Key:



Once you have obtained a valid access token, you can now make a web service request.

Step 2: Prepare the Parameters

Get from your IT System the amount(s) from which the commission will be computed from.

Pass these value(s) to your spreadsheet containing the following tabs (In, Out, Other Tabs):

Tab / Cell Description
In Tab: Tab where you define the input parameters, in this case the Amount and Product Type Incentive
B1 Amount from which the Commission will be computed against
B2 Product Type Incentive that determines the corresponding Incentive Amount
Out Tab: Tab where you get the output values, in this case the Commission Amount and Incentive Amount
B5 The Commission Amount that we need to get using the “compute” web service
B6 The Incentive Amount that we also need to get
Other Tabs Other tabs for defining the formulae for computing the Commission Amount

Define an array object where you can store all the parameters and parameter values that you need to pass to the web service.

The code below assigns the input values for In Tab Cells B1 (from IT System Sales Amount) and B2 (from IT System Product Type Incentive), and indicates that the “compute” output will be from Out Tab Cells B5 and B6.

// Get the values of the Sales Amount and Product Type Incentive from the IT System
$salesAmount = 12000;
$productType = "TYPE03";

// Define the parameters and parameter values that you need to pass to the web service
$param = array();
$param["cfxlArchive"]="False";

// Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
$param["In!B1"]="[\"IN\",\"".$salesAmount."\"]";
$param["In!B2"]="[\"IN\",\"".$productType."\"]";

// Define that the output parameters will come from Out Tab Cells B5 and B6
$param["Out!B5"]="[\"OUT\"]";
$param["Out!B6"]="[\"OUT\"]";

$param["cfxlCustom"]="This is a custom parameter.";

All the other parameters, such as cfxlArchive, and cfxlCustom will be discussed in detail in the Web Service REST API section.




















Step 3: Make an API Call

To get the result of a computation, issue a “compute” web service request.

To do this, define a String variable where you can store the result of your request.

From this String variable, issue the applicable method call:

For WordPress pages:
$result = wp_calcfusion_request_service("compute/386", "GET", $param);

For Non-WordPress pages:
$result = $cfClient->requestService("compute/386", "GET", $param);

Result:
{
"response":
     { "errorMessage": "",
     "status": "OK",
     "errorCode": "" },
"requestId": 20140710a1733r45823egfuw,
"cfxlContextInfo": "PHP 1.0.0",
"cfxlCustom": "This is my Custom Parameter",
"data":
[
     { "Out!B5": 1200.0, "Out!B6": 60.0 }
]
}

It is through the “requestService” and “wp_calcfusion_request_service” methods that you specify the “compute” web service request (including the web service path parameters),

The request method (in this case, GET), and the request parameter (the param array).

When a CalcFusion web service is called, the result will return the following information: Request ID, Response Status, Data, Custom Parameter and Context Info.

It is from the Data where you can get the value of the computation you want (in this example, Cell B5).








Step 4: Error Handling

If an error has occurred while processing the request, the error message will be returned as part of the Response Status result.

Below is an example of a response in JSON format that contains an error:

{
“response”:
    { “errorMessage”: “Username was not specified (CF: 1010)”,
    “status”: “FAILED”,
    “errorCode”: “400” },
“requestId”: 20140710a1733r45823egfuw,
“cfxlContextInfo”: “PHP 1.0.0”,
“cfxlCustom”: “This is my Custom Parameter”,
“data”: null
}

Full PHP code

<?php
require_once "calcfusion-api-1.0.0.phar";

// Get the values of the Sales Amount and Product Type Incentive from the IT System
$salesAmount = 12000;
$productType = "TYPE03";

// Define the parameters and parameter values that you need to pass to the web service
$param = array();
$param["cfxlArchive"]="False";

// Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
$param["In!B1"]="[\"IN\",\"".$salesAmount."\"]";
$param["In!B2"]="[\"IN\",\"".$productType."\"]";

// Define that the output parameters will come from Out Tab Cells B5 and B6
$param["Out!B5"]="[\"OUT\"]";
$param["Out!B6"]="[\"OUT\"]";

$param["cfxlCustom"]="This is a custom parameter.";

// Use the requestService method to issue a web service request and specify the request method and parameters
$result = wp_calcfusion_request_service("compute/386", "GET", $param);

// Display the result of the web service request (JSON format)
print_r($result);

// Retrieve the Response Status and Error Message from the result

// First, convert the JSON response result into an Array
$resultMap = json_decode($result,true);

if($resultMap) {
    // "response" contains the Status, Error Code and Error Message
    $resultResponse = $resultMap["response"];

    if($resultResponse && strtolower($resultResponse ["status"])=="failed") {
        // Then display the Status and Error Message
        print_r($resultResponse ["status"]);
        print_r($resultResponse ["errorMessage"]);
        break;
    }

    // "data" contains the data requested by the output parameters
    $dataList = $resultMap["data"];

    // Get and display the Commission
    $commission = $dataList["Out!B5"];
    print_r($commission);

    // Get and display the Incentive
    $incentive = $dataList["Out!B6"];
    print_r($incentive);
}
?>



























































<?php
require_once "../wp-config.php" ;
require_once ABSPATH."/wp-content/plugins/calcfusion-wp/core/calcfusion-api-1.0.0.phar";

$cfClient=new CalcFusionClient("https://api.calcfusion.com/CalcFusion-Core-WebServices/rest");
$accessToken =$cfClient->login($username, $password, $accountID, $appkey);

if($accessToken) {
    // Get the values of the Sales Amount and Product Type Incentive from the IT System
    $salesAmount = 12000;
    $productType = "TYPE03";

    // Define the parameters and parameter values that you need to pass to the web service
    $param = array();
    $param["cfxlArchive"]="False";

    // Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
    $param["In!B1"]="[\"IN\",\"".$salesAmount."\"]";
    $param["In!B2"]="[\"IN\",\"".$productType."\"]";

    // Define that the output parameters will come from Out Tab Cells B5 and B6
    $param["Out!B5"]="[\"OUT\"]";
    $param["Out!B6"]="[\"OUT\"]";

    $param["cfxlCustom"]="This is a custom parameter.";

    // Use the requestService method to issue a web service request and specify the request method and parameters
    $result = $cfClient->requestService("compute/386", "GET", $param);

    // Display the result of the web service request (JSON format)
    print_r($result);

    // Retrieve the Response Status and Error Message from the result
    // First, convert the JSON response result into an Array
    $resultMap = json_decode($result,true);

    if($resultMap) {
        // "response" contains the Status, Error Code and Error Message
        $resultResponse = $resultMap["response"];

        if($resultResponse && strtolower($resultResponse ["status"])=="failed") {
            // Then display the Status and Error Message
            print_r($resultResponse ["status"]);
            print_r($resultResponse ["errorMessage"]);
            break;
        }

        // "data" contains the data requested by the output parameters
        $dataList = $resultMap["data"];

        // Get and display the Commission
        $commission = $dataList["Out!B5"];
        print_r($commission);

        // Get and display the Incentive
        $incentive = $dataList["Out!B6"];
        print_r($incentive);
    }
}
?>

Java

Intro

There are 2 ways to send web service requests using the Core API – the Synchronous and Asynchronous API calls:

The Core API inside the calcfusion package contains the following classes that allow for asynchronous and synchronous REST API calls:

Core Library

The CalcFusionClient Class

The CalcFusionClient class provides the methods for sending CalcFusion credentials, obtaining access tokens and managing web service requests between an IT System and CalcFusion.

These are the methods available in this class:

CalcFusionClient cfClient = new CalcFusionClient("https://api.calcfusion.com/CalcFusion-Core-WebServices/rest");
HashMap parameters = new HashMap();
parameters.put("cfxlCustom", "This is a custom parameter.");
String cAccessToken = cfClient.login(username, password, accountID, appkey, parameters);

The login method initiates the OAuth 2.0 authentication process.

By passing the email, password, accountID and appKey as parameters, a valid access token is returned if authentication is successful, otherwise it returns an error message.

The AsyncRequestRunnable class is referenced by the methods of CalcFusionClient for executing asynchronous client request calls.

The CalcFusionClient class already manages the processes needed for executing asynchronous requests, so there is no need to build your own code.

The next section provides more details on how to make asynchronous requests.

// Get the values of the Sales Amount and Product Type Incentive from the IT System
Double salesAmount = (Double) dataObject.get("salesAmount");
String productType = (String) dataObject.get("productType");

// Define the parameters and parameter values that you need to pass to the web service
HashMap param = new HashMap();
param.put("cfxlArchive", "False");

// Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
param.put("In!B1", "[\"IN\",\""+ salesAmount +"\"]");
param.put("In!B2", "[\"IN\",\""+ productType + "\"]");

// Define that the output parameters will come from Out Tab Cells B5 and B6
param.put("Out!B5", "[\"OUT\"]");
param.put("Out!B6", "[\"OUT\"]");
param.put("cfxlCustom", "This is a custom parameter.");

String result = cfClient.requestService("compute/386", "GET", param);

The requestService method manages all web service requests from an IT System. It works by creating a HTTP request for a RESTful web service request.

The servicePath refers to the URL path that will handle the web service request (including the web service path parameters).

The method refers to the HTTP request method to use (GET/POST). The parameters refers to the HTTP parameters required by the servicePath in key-value pair form (see Notes below).

After processing the request, it will return data in String format (formatted in JSON). An error message will be returned if an error has occurred.









The logout method provides a means to invalidate an existing access token.

Alternately, you can invalidate an existing access token by calling the span “token/logout” web service (see Notes below).

// x Asynchronous web service calls using the same parameter values
ArrayList asyncRequestIdList = new ArrayList();

for (int i = 0; i < 10; i++)
{
      // Get the values of the Sales Amount and Product Type Incentive from the IT System
      Double salesAmount = 12000;
      String productType = "TYPE03";

      // Define the parameters and parameter values that you need to pass to the web service
      HashMap param = new HashMap();
      param.put("cfxlArchive", "False");

      // Define the input parameters and pass the Sales Amount and Product Type Incentive as    parameter values
      param.put("In!B1", "[\"IN\",\""+ salesAmount +"\"]");
      param.put("In!B2", "[\"IN\",\""+ productType + "\"]");

      // Define that the output parameters will come from Out Tab Cells B5 and B6
      param.put("Out!B5", "[\"OUT\"]");
      param.put("Out!B6", "[\"OUT\"]");

     param.put("cfxlCustom", "This is a custom parameter.");

      // Use the asyncRequestService method to issue an asynchronous web service request and
      specify the request method and parameters
      String asyncRequestId = cfClient.asyncRequestService("compute/386", "GET", param);

      // Put the Request Id in an Array List to be able to check the results later
      asyncRequestIdList.add(asyncRequestId);
}

The asyncRequestService method manages all asynchronous web service requests from an IT System.

It processes requests the same way as that of requestService, but it does not wait for a response before the next request is processed.































* asyncCallbackResult(asyncRequestId, result)

The asyncCallbackResult method serves as a listener for the result of the asynchronous request.

This is called by the AsyncRequestRunnable class when a response is already available.

The result is stored in a resultStorage collection referenced by the provided asyncRequestId.

//Define the Array List for checking the results of each request
Map<String, HashMap> resultStorage = Collections.synchronizedMap(new HashMap<String, HashMap>());
ArrayList asyncResultList = new ArrayList();

while(asyncResultList.size() != asyncRequestIdList.size())
{
     for(int i = 0; i < asyncRequestIdList.size(); i++)
      {
            String asyncRequestId = (String)asyncRequestIdList.get(i);

            // Check if there is already a result for a specific Request Id
            requestResult = cfClient.getAsyncRequestResult(asyncRequestId);

            // If no result yet, check the next Request Id
            if(requestResult == null)
            continue;

            // If there is a result already, put it in the result list
            Long requestEnd = new Date().getTime();
            HashMap resultObj = new HashMap();
            resultObj.put("requestResult", requestResult);
            resultObj.put("requestEnd", requestEnd);
            asyncResultList.add(resultObj);
            resultStorage.put(asyncRequestId, resultObj);
}

          // Implement a delay before restarting the checking(50 miliseconds)
          Thread.sleep(50);
}

//Can now display the result or can be processed by going through the items inside asyncResultList
for(int i = 0; i < asyncRequestIdList.size(); i++)
{
      String asyncRequestId = (String)asyncRequestIdList.get(i);
      HashMap resultObj = resultStorage.get(asyncRequestId);
      if(resultObj != null)
            resultStorage.remove(asyncRequestId);

      if(resultObj != null)
      {
            requestResult = (String)resultObj.get("requestResult");
            HashMap resultData = gson.fromJson(requestResult, HashMap.class);

           out.println(resultData.get("data"));
      }
}

resultStorage.clear();
asyncRequestIdList.clear();
resultStorage.clear();

The getAsyncRequestResult method is used to check and retrieve if the synchronous service request has already returned a result.




















































String libInfo = cfClient.getContextInfo();

The getContextInfo()method below returns library information such as Context, Version and File Name in JSON format.

Sample Implementation

Sample Scenario

Compute the Commission Amount from a spreadsheet using CalcFusion, then display the amount on your IT System.

For this, you need to do the following steps:

Implementation

Step 1: Setup Authentication

CalcFusionClient cfClient = new CalcFusionClient("https://api.calcfusion.com/CalcFusion-Core-WebServices/rest");

Create an instance of a CalcFusionClient class, passing the root URL of the CalcFusion web services:


HashMap parameters = new HashMap();
parameters.put("cfxlCustom", "This is a custom parameter.");
String cAccessToken = cfClient.login(username, password, accountID, appkey, parameters);

Obtain an access token by sending your CalcFusion credentials – Email, Password (encrypted using SHA-1), Account ID and App Key:




The cfxlCustom parameter, which is optional, will be discussed in detail in the Web Service REST API section. Once you have obtained a valid access token, you can now make a web service request.

Step 2: Make an API Call

//Get the values of the Sales Amount and Product Type Incentive from the IT System
Double salesAmount = (Double) dataObject.get("salesAmount");
String productType = (String) dataObject.get("productType");

//Define the parameters and parameter values that you need to pass to the web service
HashMap param = new HashMap();
param.put("cfxlArchive", "False");

//Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
param.put("In!B1", "[\"IN\",\"" + salesAmount + "\"]");
param.put("In!B2", "[\"IN\",\"" + productType + "\"]");

//Define that the output parameters will come from Out Tab Cells B5 and B6
param.put("Out!B5", "[\"OUT\"]");
param.put("Out!B6", "[\"OUT\"]"); 

param.put("cfxlCustom", "This is a custom parameter.");

String result = cfClient.requestService("compute/386", "GET", param);

Result:
{
 "response":
              { "errorMessage": "",
              "status": "OK",
              "errorCode": "" },
   "requestId": 20140710a1733r45823egfuw,
   "cfxlContextInfo": "Java 1.0.0",
   "cfxlCustom": "This is my Custom Parameter",
   "data":
   [
           { "Out!B5": 1200.0, "Out!B6": 60.0 }
   ]
}

Get from your IT System the amount(s) from which the commission will be computed from. Pass these value(s) to your spreadsheet containing the following tabs (In, Out, Other Tabs):

Tab / Cell Description
IN Tab Tab where you define the input parameters, in this case the Amount and Product Type Incentive
B1 Amount from which the Commission will be computed against
B2 Product Type Incentive that determines the corresponding Incentive Amount
Out Tab Tab where you get the output values, in this case the Commission Amount and Incentive Amount
B5 The Commission Amount that we need to get using the “compute” web service
B6 The Incentive Amount that we also need to get
Other tabs Other tabs for defining the formulae for computing the Commission Amount

To get the result of a computation, issue a “compute” web service request.

Define a HashMap object where you can store all the parameters and parameter values that you need to pass to the web service.

The code below assigns the input values for In Tab Cells B1 (from IT System Sales Amount) and B2 (from IT System Product Type Incentive), and indicates that the “compute” output will be from Out Tab Cells B5 and B6.

All the other parameters, such as cfxlArchive, and cfxlCustom will be discussed in detail in the REST API Library section.

When a CalcFusion web service is called, the result will return the following information: Request ID, Response Status, Data, Custom Parameter and Context Info. It is from the Data where you can get the value of the computation you want (in this example, Cell B5).

To logout from CalcFusion and invalidate the access token, you need to issue a “logout” method call from the CalcFusionClient instance (cfClient).

Note that it is not necessary to logout from CalcFusion each time you send a web service request.

Step 3: Error Handling

<%@page import="java.util.HashMap"%>
<%@page import="java.util.ArrayList"%>
<%@page import="calcfusion.CalcFusionClient"%>
<%@page import="com.google.gson.internal.LinkedTreeMap"%>
<%@page import="com.google.gson.GsonBuilder"%>
<%@page import="com.google.gson.Gson"%>

<%
//Set up authentication
CalcFusionClient cfClient = new CalcFusionClient("https://api.calcfusion.com/CalcFusion-Core-WebServices/rest");

//Retrieve a valid access token by sending your CalcFusion credentials
String username = <Username>;
String password = <Password>;
String accountID = <Account ID>;
String appkey = <AppKey>;

HashMap parameters = new HashMap();
parameters.put("cfxlCustom", "This is a custom parameter.");

String cAccessToken = cfClient.login(username, password, accountID, appkey, parameters);

HashMap dataObject = new HashMap();
dataObject.put("salesAmount", <Sales Amount value>);
dataObject.put("productType", <Product Type value>);

//Check if there is a valid access token
if(cAccessToken != null) {
    //Get the values of the Sales Amount and Product Type Incentive from the IT System
    Double salesAmount = (Double) dataObject.get("salesAmount");
    String productType = (String) dataObject.get("productType");

    //Define the parameters and parameter values that you need to pass to the web service
    HashMap param = new HashMap();
    param.put("cfxlArchive", "False");

    //Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
    param.put("In!B1", "[\"IN\",\"" + salesAmount + "\"]");
    param.put("In!B2", "[\"IN\",\"" + productType + "\"]");

    //Define that the output parameters will come from Out Tab Cells B5 and B6
    param.put("Out!B5", "[\"OUT\"]");
    param.put("Out!B6", "[\"OUT\"]"); 

    param.put("cfxlCustom", "This is a custom parameter.");

    //Use the requestService method to issue a web service request and specify the request method and parameters
    String result = cfClient.requestService("compute/386", "GET", param);

    //Display the result of the web service request (JSON format)
    out.println("<div><b>RESULT: </b>" + result + "<div>");

    //Retrieve the Response Status and Error Message from the result
    //First, convert the JSON response result into a HashMap
    Gson gson = new GsonBuilder()
         .enableComplexMapKeySerialization()
         .serializeNulls()
         .setPrettyPrinting()
         .disableHtmlEscaping()
         .create();
    HashMap resultData = gson.fromJson(result, HashMap.class);

    //Because "response" contains the Status, Error Code and Error Message,
    //convert it to a LinkedTreeMap for easier data retrieval
    LinkedTreeMap resultResponse = (LinkedTreeMap)resultData.get("response");

    //Then display the Status and Error Message from the LinkedTreeMap
    String status = (String)resultResponse.get("status");
    String errorMsg = (String)resultResponse.get("errorMessage");

    if (status.equalsIgnoreCase("OK")) {
        out.println("No error.");

        //Convert "data" to a LinkedTreeMap for easier data retrieval
        ArrayList resultResponseData = (ArrayList)resultData.get("data");
        LinkedTreeMap dataObj = (LinkedTreeMap)resultResponseData.get(0);

        //Then get and display the Data from the LinkedTreeMap
        Double commission = (Double) dataObj.get("Out!B5");
        out.println("Commission Amount = " + commission);

        Double incentive = (Double) dataObj.get("Out!B6");
        out.println("Incentive Amount = " + incentive);
    } else {
        out.println("Error Message:" + errorMsg);
    }
}%>

If an error has occurred while processing the request, the error message will be returned as part of the Response Status result.

Below is an example of a response in JSON format that contains an error:

{
“response”:
    { “errorMessage”: “Username was not specified (CF: 1010)”,
    “status”: “FAILED”,
    “errorCode”: “400” },
“requestId”: 20140710a1733r45823egfuw,
“cfxlContextInfo”: “Java 1.0.0”,
“cfxlCustom”: “This is my Custom Parameter”,
“data”: null
}

Please refer to the Error Handling section for a list of error codes.

PHP

Intro

There are 2 ways to send web service requests using the Core API – the Synchronous and Asynchronous API calls:

The Core API inside the “calcfusion-api-1.0.0.phar” contains the following classes that allow for asynchronous and synchronous REST API calls:

Core Library

The CalcFusionClient Class

The CalcFusionClient class provides the methods for sending CalcFusion credentials, obtaining access tokens and managing web service requests between an IT System and CalcFusion.

These are the methods available in this class:

$cfClient=new CalcFusionClient("https://api.calcfusion.com/CalcFusion-Core-WebServices/rest");
$parameters = array();
$parameters["cfxlCustom"] = "This is a custom parameter.";
$accessToken = $cfClient->login($username, $password, $accountID, $appkey, $parameters);

The login method initiates the OAuth 2.0 authentication process.

By passing the email, password, accountID and appKey as parameters, a valid access token is returned if authentication is successful, otherwise it returns an error message.

The refreshToken method provides a means to refresh an existing access token (by passing it as an array parameter).

// Get the values of the Sales Amount and Product Type Incentive from the IT System
$salesAmount = 12000;
$productType = "TYPE03";

// Define the parameters and parameter values that you need to pass to the web service
$param = array();
$param["cfxlArchive"]="False";

// Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
$param["In!B1"]="[\"IN\",\"".$salesAmount."\"]";
$param["In!B2"]="[\"IN\",\"".$productType."\"]";

// Define that the output parameters will come from Out Tab Cells B5 and B6
$param["Out!B5"]="[\"OUT\"]";
$param["Out!B6"]="[\"OUT\"]";
$param["cfxlCustom"]="This is a custom parameter.";

$result = $cfClient->requestService("compute/386", "GET", $param);

The requestService method manages all web service requests from an IT System. It works by creating a HTTP request for a RESTful web service request.

The servicePath refers to the URL path that will handle the web service request (including the web service path parameters).

The method refers to the HTTP request method to use (GET/POST). The parameters refers to the HTTP parameters required by the servicePath in key-value pair form (see Notes below).

After processing the request, it will return data in String format (formatted in JSON). An error message will be returned if an error has occurred.









The logout method provides a means to invalidate an existing access token.

Alternately, you can invalidate an existing access token by calling the span “token/logout” web service (see Notes below).

// Get the values of the Sales Amount and Product Type Incentive from the IT System
$salesAmount = 12000;
$productType = "TYPE03";

// Define the parameters and parameter values that you need to pass to the web service
$param = array();
$param["cfxlArchive"]="False";

// Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
$param["In!B1"]="[\"IN\",\"".$salesAmount."\"]";
$param["In!B2"]="[\"IN\",\"".$productType."\"]";

// Define that the output parameters will come from Out Tab Cells B5 and B6
$param["Out!B5"]="[\"OUT\"]";
$param["Out!B6"]="[\"OUT\"]";
$param["cfxlCustom"]="This is a custom parameter.";

$result = $cfClient->requestService("compute/386", "GET", $param);

The asyncRequestService method manages all asynchronous web service requests from an IT System.

It processes requests the same way as that of requestService, but it does not wait for a response before the next request is processed.

















* asyncCallbackResult(asyncRequestId, result)

The asyncCallbackResult method serves as a listener for the result of the asynchronous request.

This is called by the AsyncRequestRunnable class when a response is already available.

The result is stored in a resultStorage collection referenced by the provided asyncRequestId.

// Define the Array List for checking the results of each request
$resultStorage = array();

while(count($resultStorage) != count($asyncRequestIdList)) {

      for($i=0; $i < count($asyncRequestIdList); $i++)      {          $asyncRequestId = $asyncRequestIdList[$i];          // Check if there is already a result for a specific Request Id          $requestResult = $cfClient->getAsyncRequestResult($asyncRequestId);
         // If no result yet, check the next Request Id
        if($requestResult == null)
         continue;


         // If there is a result already, put it in the result list
         $resultStorage[$asyncRequestId] = $requestResult;
      }


      // Implement a delay before restarting the checking(50 miliseconds)
      sleep(.5);
}
// Can now display the result or can be processed by going through the items inside asyncResultList
for($j=0; $j < count($asyncRequestIdList); $j++)
{
      $asyncRequestId = $asyncRequestIdList[$j];
      $requestResult = $resultStorage[$asyncRequestId];
      print_r($requestResult);
      print_r("");
}
unset($resultStorage);
unset($asyncRequestIdList);
unset($resultStorage);

The getAsyncRequestResult method is used to check and retrieve if the synchronous service request has already returned a result.
































$libInfo = $cfClient->getContextInfo();

The getContextInfo()method below returns library information such as Context, Version and File Name in JSON format.

Sample Implementation

Sample Scenario

Compute the Commission Amount from a spreadsheet using CalcFusion, then display the amount on your IT System.

For this, you need to do the following steps:

Implementation

Step 1: Setup Authentication

$cfClient=new CalcFusionClient("https://api.calcfusion.com/CalcFusion-Core-WebServices/rest");

Create an instance of a CalcFusionClient class, passing the root URL of the CalcFusion web services:


$parameters = array();
$parameters["cfxlCustom"] = "This is a custom parameter.";
$accessToken = $cfClient->login($username, $password, $accountID, $appkey, $parameters);

Obtain an access token by sending your CalcFusion credentials – Email, Password (encrypted using SHA-1), Account ID and App Key:




The cfxlCustom parameter, which is optional, will be discussed in detail in the Web Service REST API section. Once you have obtained a valid access token, you can now make a web service request.

Step 2: Make an API Call

 // Get the values of the Sales Amount and Product Type Incentive from the IT System
$salesAmount = 12000;
$productType = "TYPE03";

// Define the parameters and parameter values that you need to pass to the web service
$param = array();
$param["cfxlArchive"]="False";

// Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
$param["In!B1"]="[\"IN\",\"".$salesAmount."\"]";
$param["In!B2"]="[\"IN\",\"".$productType."\"]";

// Define that the output parameters will come from Out Tab Cells B5 and B6
$param["Out!B5"]="[\"OUT\"]";
$param["Out!B6"]="[\"OUT\"]";

$param["cfxlCustom"]="This is a custom parameter.";

$result = $cfClient->requestService("compute/386", "GET", $param);

Result:
{
"response":
            { "errorMessage": "",
            "status": "OK",
            "errorCode": "" },
"requestId": 20140710a1733r45823egfuw,
"cfxlContextInfo": "PHP 1.0.0",
"cfxlCustom": "This is my Custom Parameter",
"data":
[
                 { "Out!B5": 1200.0, "Out!B6": 60.0 }
]
} 

Get from your IT System the amount(s) from which the commission will be computed from. Pass these value(s) to your spreadsheet containing the following tabs (In, Out, Other Tabs):

Tab / Cell Description
IN Tab Tab where you define the input parameters, in this case the Amount and Product Type Incentive
B1 Amount from which the Commission will be computed against
B2 Product Type Incentive that determines the corresponding Incentive Amount
Out Tab Tab where you get the output values, in this case the Commission Amount and Incentive Amount
B5 The Commission Amount that we need to get using the “compute” web service
B6 The Incentive Amount that we also need to get
Other tabs Other tabs for defining the formulae for computing the Commission Amount

To get the result of a computation, issue a “compute” web service request.

Define an array object where you can store all the parameters and parameter values that you need to pass to the web service.

The code below assigns the input values for In Tab Cells B1 (from IT System Sales Amount) and B2 (from IT System Product Type Incentive), and indicates that the “compute” output will be from Out Tab Cells B5 and B6.

All the other parameters, such as cfxlArchive, and cfxlCustom will be discussed in detail in the REST API Library section.

When a CalcFusion web service is called, the result will return the following information: Request ID, Response Status, Data, Custom Parameter and Context Info. It is from the Data where you can get the value of the computation you want (in this example, Cell B5).

To logout from CalcFusion and invalidate the access token, you need to issue a “logout” method call from the CalcFusionClient instance (cfClient).

Note that it is not necessary to logout from CalcFusion each time you send a web service request.

Step 3: Error Handling

<?php
require_once "calcfusion-api-1.0.0.phar";

$cfClient=new CalcFusionClient("https://api.calcfusion.com/CalcFusion-Core-WebServices/rest");

$parameters = array();
$parameters["cfxlCustom"] = "This is a custom parameter.";
$accessToken = $cfClient->login($username, $password, $accountID, $appkey, $parameters);

if($accessToken){
// Get the values of the Sales Amount and Product Type Incentive from the IT System
$salesAmount = 12000;
$productType = "TYPE03";
// Define the parameters and parameter values that you need to pass to the web service
$param = array();
$param["cfxlArchive"]="False";
// Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
$param["In!B1"]="[\"IN\",\"".$salesAmount."\"]";
$param["In!B2"]="[\"IN\",\"".$productType."\"]";
// Define that the output parameters will come from Out Tab Cells B5 and B6
$param["Out!B5"]="[\"OUT\"]";
$param["Out!B6"]="[\"OUT\"]";
$param["cfxlCustom"]="This is a custom parameter.";
// Use the requestService method to issue a web service request and specify the request method and parameters
$result = $cfClient->requestService("compute/386", "GET", $param);
// Display the result of the web service request (JSON format)
print_r($result);
// Retrieve the Response Status and Error Message from the result
// First, convert the JSON response result into an Array
$resultMap = json_decode($result,true);
if($resultMap)
{
// "response" contains the Status, Error Code and Error Message
$resultResponse = $resultMap["response"];
if($resultResponse && strtolower($resultResponse ["status"])=="failed")
{
// Then display the Status and Error Message
print_r($resultResponse ["status"]);
print_r($resultResponse ["errorMessage"]);
break;
}
// "data" contains the data requested by the output parameters
$dataList = $resultMap["data"];
// Get and display the Commission
$commission = $dataList["Out!B5"];
print_r($commission);
// Get and display the Incentive
$incentive = $dataList["Out!B6"];
print_r($incentive);
}
// To refresh the access token
$result=$cfClient->refreshToken();
print_r($result);
// To logout
$result=$cfClient->logout();
print_r($result);
}
?>

If an error has occurred while processing the request, the error message will be returned as part of the Response Status result.

Below is an example of a response in JSON format that contains an error:

{
“response”:
    { “errorMessage”: “Username was not specified (CF: 1010)”,
    “status”: “FAILED”,
    “errorCode”: “400” },
“requestId”: 20140710a1733r45823egfuw,
“cfxlContextInfo”: “PHP 1.0.0”,
“cfxlCustom”: “This is my Custom Parameter”,
“data”: null
}

Please refer to the Error Handling section for a list of error codes.

C Sharp

Intro

There are 2 ways to send web service requests using the Core API – the Synchronous and Asynchronous API calls:

CalcFusionClient contains methods that allow for asynchronous and synchronous REST API calls:

Core Library

The CalcFusionClient Class

The CalcFusionClient class provides the methods for sending CalcFusion credentials, obtaining access tokens and managing web service requests between an IT System and CalcFusion.

These are the methods available in this class:

var cfClient = new CalcFusionClient("https://api.calcfusion.com/CalcFusion-Core-WebServices/rest");
var parameters = new RequestParameter();
parameters.Add("cfxlCustom", "This is a custom parameter.");

dynamic cAccessToken = cfClient.Login(username, password, accountID, appkey, parameters);

The login method initiates the OAuth 2.0 authentication process.

By passing the email, password, accountID and appKey as parameters, a valid access token is returned if authentication is successful, otherwise it returns an error message.

The RefreshToken method provides a means to refresh an existing access token (by passing it as a RequestParameter parameter).

// Get the values of the Sales Amount and Product Type Incentive from the IT System
var salesAmount = (double) dataObject.get("salesAmount");
var productType = (string) dataObject.get("productType");

// Define the parameters and parameter values that you need to pass to the web service
var param = new RequestParamter();
param.Add("cfxlArchive", "False");

// Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
param.Add("In!B1", "[\"IN\",\""+ salesAmount +"\"]");
param.Add("In!B2", "[\"IN\",\""+ productType + "\"]");

// Define that the output parameters will come from Out Tab Cells B5 and B6
param.Add("Out!B5", "[\"OUT\"]");
param.Add("Out!B6", "[\"OUT\"]");
param.Add("cfxlCustom", "This is a custom parameter.");

dynamic result = cfClient.RequestService("compute/386", RequestMethod.GET, param);

The requestService method manages all web service requests from an IT System. It works by creating a HTTP request for a RESTful web service request.

The servicePath refers to the URL path that will handle the web service request (including the web service path parameters).

The method refers to the HTTP request method to use (GET/POST). The parameters refers to the HTTP parameters required by the servicePath in key-value pair form (see Notes below).

After processing the request, it will return data in String format (formatted in JSON). An error message will be returned if an error has occurred.









The logout method provides a means to invalidate an existing access token.

Alternately, you can invalidate an existing access token by calling the span “token/logout” web service (see Notes below).

static void Main(string[] args)
{
     var tasks = new List();

     for (int i = 0; i < 10; i++)  {  tasks.Add(DoCompute());  }  while (tasks.Count > 0)
 {
 // Identify the first task that completes
 var completedTask = Task.WhenAny(tasks);

 // Remove the task that are completed from the list
 tasks.Remove(completedTask.Result);

 // Get the dynamic object result of the async request
 var result = completedTask.Result.Result;

 Console.WriteLine(result.data);
 }
}

static async Task DoCompute()
{
 // Get the values of the Sales Amount and Product Type Incentive from the IT System
 double salesAmount = 12000;
 string productType = "TYPE03";

 // Define the parameters and parameter values that you need to pass to the web service
     var parameters = new RequestParameter();
     parameters.Add("cfxlArchive", "False");
     parameters.Add("In!B1", "[\"IN\",\"" + salesAmount + "\"]");
     parameters.Add("In!B2", "[\"IN\",\"" + productType + "\"]");
     parameters.Add("Out!B5", "[\"OUT\"]");
     parameters.Add("Out!B6", "[\"OUT\"]");
     parameters.Add("cfxlCustom", "This is a custom parameter");

     // Use the RequestServiceAsync method to issue an asynchronous web service request and specify the request method and parameters
     return await cfClient.RequestServiceAsync("compute/386", RequestMethod.GET, parameters);
}

The asyncRequestService method manages all asynchronous web service requests from an IT System.

It processes requests the same way as that of requestService, but it does not wait for a response before the next request is processed.




































* asyncCallbackResult(asyncRequestId, result)

The asyncCallbackResult method serves as a listener for the result of the asynchronous request.

This is called by the AsyncRequestRunnable class when a response is already available.

The result is stored in a resultStorage collection referenced by the provided asyncRequestId.

The getAsyncRequestResult method is used to check and retrieve if the synchronous service request has already returned a result.

dynamic libInfo = cfClient.ContextInfo;

The getContextInfo()method below returns library information such as Context, Version and File Name in JSON format.

Sample Implementation

Sample Scenario

Compute the Commission Amount from a spreadsheet using CalcFusion, then display the amount on your IT System.

For this, you need to do the following steps:

Implementation

Step 1: Setup Authentication

var cfClient = new CalcFusionClient("https://api.calcfusion.com/CalcFusion-Core-WebServices/rest");

Create an instance of a CalcFusionClient class, passing the root URL of the CalcFusion web services:


var parameters = new RequestParameter();
parameters.Add("cfxlCustom", "This is a custom parameter.");
dynamic cAccessToken = cfClient.login(username, password, accountID, appkey, parameters);

Obtain an access token by sending your CalcFusion credentials – Email, Password (encrypted using SHA-1), Account ID and App Key:




The cfxlCustom parameter, which is optional, will be discussed in detail in the Web Service REST API section. Once you have obtained a valid access token, you can now make a web service request.

Step 2: Make an API Call

// Get the values of the Sales Amount and Product Type Incentive from the IT System
var salesAmount = dataObject.Get("salesAmount");
var productType = dataObject.Get("productType");

// Define the parameters and parameter values that you need to pass to the web service
var param = new RequestParameter();
param.Add("cfxlArchive", "False");

// Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
param.Add("In!B1", "[\"IN\",\""+ salesAmount +"\"]");
param.Add("In!B2", "[\"IN\",\""+ productType + "\"]");

// Define that the output parameters will come from Out Tab Cells B5 and B6
param.Add("Out!B5", "[\"OUT\"]");
param.Add("Out!B6", "[\"OUT\"]");

param.Add("cfxlCustom", "This is a custom parameter.");

dynamic result = cfClient.RequestService("compute/386", RequestMethod.GET, param);

Result:
{
   "response":
              { "errorMessage": "",
              "status": "OK",
              "errorCode": "" },
   "requestId": 20140710a1733r45823egfuw,
   "cfxlContextInfo": "CSharp 1.0.0",
   "cfxlCustom": "This is my Custom Parameter",
   "data":
   [
           { "Out!B5": 1200.0, "Out!B6": 60.0 }
   ]
}

Get from your IT System the amount(s) from which the commission will be computed from. Pass these value(s) to your spreadsheet containing the following tabs (In, Out, Other Tabs):

Tab / Cell Description
IN Tab Tab where you define the input parameters, in this case the Amount and Product Type Incentive
B1 Amount from which the Commission will be computed against
B2 Product Type Incentive that determines the corresponding Incentive Amount
Out Tab Tab where you get the output values, in this case the Commission Amount and Incentive Amount
B5 The Commission Amount that we need to get using the “compute” web service
B6 The Incentive Amount that we also need to get
Other tabs Other tabs for defining the formulae for computing the Commission Amount

To get the result of a computation, issue a “compute” web service request.

Define a RequestParameter object where you can store all the parameters and parameter values that you need to pass to the web service.

The code below assigns the input values for In Tab Cells B1 (from IT System Sales Amount) and B2 (from IT System Product Type Incentive), and indicates that the “compute” output will be from Out Tab Cells B5 and B6.

All the other parameters, such as cfxlArchive, and cfxlCustom will be discussed in detail in the REST API Library section.

When a CalcFusion web service is called, the result will return the following information: Request ID, Response Status, Data, Custom Parameter and Context Info. It is from the Data where you can get the value of the computation you want (in this example, Cell B5).

To logout from CalcFusion and invalidate the access token, you need to issue a “logout” method call from the CalcFusionClient instance (cfClient).

Note that it is not necessary to logout from CalcFusion each time you send a web service request.

Step 3: Error Handling

using CalcFusion;

// Set up authentication
var cfClient = new CalcFusionClient("https://api.calcfusion.com/CalcFusion-Core-WebServices/rest");

// Retrieve a valid access token by sending your CalcFusion credentials
var parameters = new RequestParameter();
parameters.Add("cfxlCustom", "This is a custom parameter.");
dynamic cAccessToken = cfClient.login(username, password, accountID, appkey, parameters);

// Check if there is a valid access token
if(cAccessToken != null)
{
// Get the values of the Sales Amount and Product Type Incentive from the IT System
var salesAmount = dataObject.Get<double>("salesAmount");
var productType = dataObject.Get<string>("productType");

// Define the parameters and parameter values that you need to pass to the web service
var param = new RequestParameter();
param.Add("cfxlArchive", "False");

// Define the input parameters and pass the Sales Amount and Product Type Incentive as parameter values
param.Add("In!B1", "[\"IN\",\""+ salesAmount +"\"]");
param.Add("In!B2", "[\"IN\",\""+ productType + "\"]");

// Define that the output parameters will come from Out Tab Cells B5 and B6
param.Add("Out!B5", "[\"OUT\"]");
param.Add("Out!B6", "[\"OUT\"]");

param.Add("cfxlCustom", "This is a custom parameter.");

// Use the RequestService method to issue a web service request and specify the request method and parameters
dynamic result = cfClient.RequestService("compute/386", RequestMethod.GET, param);

// Display the result of the web service request (JSON format)
Response.Write("<div><b>RESULT: </b>" + result.ToString() + </div>);

// Display the Status and Error Message from the dynamic object
var status = result.response.status.ToString();
var errorMsg = result.response.errorMessage.ToString();

if (string.Compare(status, "OK", true) == 0)
{
Response.Write("No error.");

// Display the Data from the dynamic object
var commission = result.data[0]["Out!B5"].ToString();
Response.Write("Commission Amount = " + commission);

var incentive = result.data[0]["Out!B6"].ToString();
Response.Write("Incentive Amount = " + incentive);
}
else
{
Response.Write("Error Message:" + errorMsg);
}
}

If an error has occurred while processing the request, the error message will be returned as part of the Response Status result.

Below is an example of a response in JSON format that contains an error:

{
“response”:
    { “errorMessage”: “Username was not specified (CF: 1010)”,
    “status”: “FAILED”,
    “errorCode”: “400” },
“requestId”: 20140710a1733r45823egfuw,
“cfxlContextInfo”: “CSharp 1.0.0”,
“cfxlCustom”: “This is my Custom Parameter”,
“data”: null
}

Please refer to the Error Handling section for a list of error codes.

Web Service REST API

REST API Library

Overview

The REST API provides the following resource classes:

Description

Most of the REST API services follow a standard design. The following sections provide a description of the general structure of a REST API call.

URL Structure

https://api.calcfusion.com/CalcFusion-Core-WebServices/rest/compute/386/3?cfxlArchive=False&In!B1=["IN","12000"]& Out!B5=["OUT"]&cfxlCustom=This is a custom parameter

REST API services use standard HTTP requests to access and manage resources. For example, to issue a “compute” web service call, the following HTTP request will be issued:

Method

GET /CalcFusion-Core-WebServices/rest/compute/386/3

Since REST API services use standard HTTP requests, it also uses standard HTTP methods (GET / POST). Using the example above, the request will be sent as:

Request

Although different REST API services may require different parameters to pass, these APIs follow a basic format.

Using the example above, the service request has the following parts:

Response

All REST API services provide the following response information:

The REST API services provide return values as part of the response. Return values contain: * Request ID * Response Status (OK or Failed, including the Error Code and Message if an error has been encountered) * Requested Data * Custom Parameter (Sent to the service as cfxlCustom HTTP Parameter. When a value has not been defined, the service will return it as null.) * Context Info (Automatically sent by the Core API Library as cfxlContextInfo HTTP Parameter. It returns library context information.)

Return Values Format: A REST API service always returns a String value, formatted as JSON.

Error Codes: When a request has encountered an error, CalcFusion will return the error code and message as part of the response.

Errors

Overview

After CalcFusion processes a request, it sends back the requested data. If the request has encountered an error, CalcFusion returns an error message.

Error Codes and Description

Errors are returned as standard HTTP errors, but additional information (such as the CalcFusion error code and message) will also be returned.

Error Code Meaning
400 Bad Request – Your request sucks
401 Unauthorized – Your API key is wrong
403 Forbidden – The kitten requested is hidden for administrators only
404 Not Found – The specified kitten could not be found
405 Method Not Allowed – You tried to access a kitten with an invalid method
406 Not Acceptable – You requested a format that isn’t json
410 Gone – The kitten requested has been removed from our servers
418 I’m a teapot
429 Too Many Requests – You’re requesting too many kittens! Slow down!
500 Internal Server Error – We had a problem with our server. Try again later.
503 Service Unavailable – We’re temporarially offline for maintanance. Please try again later.