diff --git a/BulkAPISampleFiles/delete.csv b/BulkAPISampleFiles/delete.csv new file mode 100644 index 0000000..9535358 --- /dev/null +++ b/BulkAPISampleFiles/delete.csv @@ -0,0 +1,5 @@ +Id +003E000001DJOfxIAH +003E000001DJOfyIAH +003E000001DJOV4IAP +003E000001DJOV5IAP \ No newline at end of file diff --git a/BulkAPISampleFiles/delete.xml b/BulkAPISampleFiles/delete.xml new file mode 100644 index 0000000..e644728 --- /dev/null +++ b/BulkAPISampleFiles/delete.xml @@ -0,0 +1,16 @@ + + + + + 003E000001DJOfxIAH + + + 003E000001DJOfyIAH + + + 003E000001DJOV4IAP + + + 003E000001DJOV5IAP + + \ No newline at end of file diff --git a/BulkAPISampleFiles/insert.csv b/BulkAPISampleFiles/insert.csv new file mode 100644 index 0000000..31cb26a --- /dev/null +++ b/BulkAPISampleFiles/insert.csv @@ -0,0 +1,3 @@ +FirstName,LastName,Department,Birthdate,Description +Tom,Jones,Marketing,1940-06-07Z,"Self-described as ""the top"" branding guru on the West Coast" +Ian,Dury,R&D,,"World-renowned expert in fuzzy logic design. Influential in technology purchases." \ No newline at end of file diff --git a/BulkAPISampleFiles/insert.xml b/BulkAPISampleFiles/insert.xml new file mode 100644 index 0000000..686ed5a --- /dev/null +++ b/BulkAPISampleFiles/insert.xml @@ -0,0 +1,17 @@ + + + + + Tom + Jones + Marketing + 1940-06-07Z + Self-described as "the top" branding guru on the West Coast + + + Ian + Dury + R&D + World-renowned expert in fuzzy logic design. Influential in technology purchases. + + \ No newline at end of file diff --git a/BulkAPISampleFiles/update.csv b/BulkAPISampleFiles/update.csv new file mode 100644 index 0000000..230ef1a --- /dev/null +++ b/BulkAPISampleFiles/update.csv @@ -0,0 +1,2 @@ +Id,Title +003E000001CbzBi,Ninja \ No newline at end of file diff --git a/BulkAPISampleFiles/update.xml b/BulkAPISampleFiles/update.xml new file mode 100644 index 0000000..8574c72 --- /dev/null +++ b/BulkAPISampleFiles/update.xml @@ -0,0 +1,8 @@ + + + + + 003E000001CbzBi + Pirate + + \ No newline at end of file diff --git a/BulkAPISampleFiles/upsert.csv b/BulkAPISampleFiles/upsert.csv new file mode 100644 index 0000000..5841c32 --- /dev/null +++ b/BulkAPISampleFiles/upsert.csv @@ -0,0 +1,2 @@ +Twitter_Handle__c,Title +pattest7,Guru \ No newline at end of file diff --git a/BulkAPISampleFiles/upsert.xml b/BulkAPISampleFiles/upsert.xml new file mode 100644 index 0000000..b942d57 --- /dev/null +++ b/BulkAPISampleFiles/upsert.xml @@ -0,0 +1,8 @@ + + + + + pattest7 + Pirate + + \ No newline at end of file diff --git a/BulkTK.md b/BulkTK.md new file mode 100644 index 0000000..a5eb38f --- /dev/null +++ b/BulkTK.md @@ -0,0 +1,137 @@ +BulkTK: Force.com Bulk API JavaScript Toolkit +============================================= + +This minimal toolkit extends ForceTK to allow JavaScript in web pages to call the [Force.com Bulk API](https://www.salesforce.com/us/developer/docs/api_asynch/). + +Background +========== + +The Force.com Bulk API allows asynchronous data access. BulkTK extends ForceTK with methods to create Bulk API jobs, add batches to them, monitor job status and retrieve job results. Control plane XML is parsed to JavaScript objects for ease of use, while data is returned verbatim. + +You should familiarize yourself with the [Force.com Bulk API documentation](https://www.salesforce.com/us/developer/docs/api_asynch/), since BulkTK is a relatively thin layer on the raw XML Bulk API. + +[bulk.page](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/bulk.page) is a simple Visualforce single page application to demonstrate BulkTK. Try it out in a sandbox or developer edition. + +Note that, just like ForceTK, BulkTK is unsupported and supplied as is. It is also currently in a very early stage of development. It appears to work well, but bugs cannot be ruled out, and the interface should not be considered stable. + +Dependencies +============ + + * [jquery](http://jquery.com/) + * [ForceTK](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) + * [jxon](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/jxon.js) (originally from the [Ratatosk](https://github.com/wireload/Ratatosk) project; this version preserves case in element and attribute names) + +Example Usage +============= + +This example focuses on Visualforce. See the [ForceTK documentation](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) for details on authenticating from an external website, such as a Heroku app, or PhoneGap/Cordova. + +First, include BulkTK and its dependencies: + + + + + + +Now create a ForceTK client: + + var client = new forcetk.Client(); + client.setSessionToken('{!$Api.Session_ID}'); + +See the [ForceTK documentation](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) for details on authenticating from an external website, such as a Heroku app, or PhoneGap/Cordova. + +Create a job +------------ + + // See https://www.salesforce.com/us/developer/docs/api_asynch/Content/asynch_api_reference_jobinfo.htm + // for details of the JobInfo structure + + // Insert Contact records in CSV format + var job = { + operation : 'insert', + object : 'Contact', + contentType : 'CSV' + }; + + client.createJob(job, function(response) { + jobId = response.jobInfo.id; + console.log('Job created with id '+jobId+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error creating job', jqXHR.responseText); + }); + +Add a batch of records to the job +--------------------------------- + +You can add multiple batches to the job; each batch can contain up to 10,000 records. See [batch size and limits](https://www.salesforce.com/us/developer/docs/api_asynch/Content/asynch_api_concepts_limits.htm#batch_size_title) for more details. + + var csvData = "FirstName,LastName,Department,Birthdate,Description\n"+ + "Tom,Jones,Marketing,1940-06-07Z,"Self-described as ""the top"" branding guru on the West Coast\n"+ + "Ian,Dury,R&D,,"World-renowned expert in fuzzy logic design. Influential in technology purchases."\n"; + + client.addBatch(jobId, "text/csv; charset=UTF-8", csvData, + function(response){ + console.log('Added batch '+response.batchInfo.id+'. State: '+response.batchInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error adding batch', jqXHR.responseText); + }); + +See BulkAPISampleFiles for sample CSV and XML data for different operations. + +Close the job +------------- + +You must close the job to inform Salesforce that no more batches will be submitted for the job. + + client.closeJob(jobId, function(response){ + console.log('Job closed. State: '+response.jobInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error closing job', jqXHR.responseText); + }); + +Check batch status +------------------ + + client.getBatchDetails(jobId, batchId, function(response){ + console.log('Batch state: '+response.batchInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch details', jqXHR.responseText); + }); + +Get batch results +----------------- + +Pass `true` as the `parseXML` parameter to get batch results for a query, false otherwise. + + client.getBatchResult(jobId, batchId, false, function(response){ + console.log('Batch result: '+response); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch result', jqXHR.responseText); + }); + +Bulk query +---------- + +When adding a batch to a bulk query job, the `contentType` for the request must be either `text/csv` or `application/xml`, depending on the content type specified when the job was created. The actual SOQL statement supplied for the batch will be in plain text format. + + var soql = 'SELECT Id, FirstName, LastName, Email FROM Contact'; + + client.addBatch(jobId, 'text/csv', soql, function(response){ + console.log('Batch state: '+response.batchInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch result', jqXHR.responseText); + }); + +Getting bulk query results is a two step process. Call `getBatchResult()` with `parseXML` set to `true` to get a set of result IDs, then call `getBulkQueryResult()` to get the actual records for each result + + client.getBatchResult(jobId, batchId, true, function(response){ + response['result-list'].result.forEach(function(resultId){ + client.getBulkQueryResult(jobId, batchId, resultId, function(response){ + console.log('Batch result: '+response); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting bulk query results', jqXHR.responseText); + }); + }); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch result', jqXHR.responseText); + }); diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..522fa4a --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,2 @@ +# Comment line immediately above ownership line is reserved for related gus information. Please be careful while editing. +#ECCN:Open Source diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..b4612a7 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,105 @@ +# Salesforce Open Source Community Code of Conduct + +## About the Code of Conduct + +Equality is a core value at Salesforce. We believe a diverse and inclusive +community fosters innovation and creativity, and are committed to building a +culture where everyone feels included. + +Salesforce open-source projects are committed to providing a friendly, safe, and +welcoming environment for all, regardless of gender identity and expression, +sexual orientation, disability, physical appearance, body size, ethnicity, nationality, +race, age, religion, level of experience, education, socioeconomic status, or +other similar personal characteristics. + +The goal of this code of conduct is to specify a baseline standard of behavior so +that people with different social values and communication styles can work +together effectively, productively, and respectfully in our open source community. +It also establishes a mechanism for reporting issues and resolving conflicts. + +All questions and reports of abusive, harassing, or otherwise unacceptable behavior +in a Salesforce open-source project may be reported by contacting the Salesforce +Open Source Conduct Committee at ossconduct@salesforce.com. + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of gender +identity and expression, sexual orientation, disability, physical appearance, +body size, ethnicity, nationality, race, age, religion, level of experience, education, +socioeconomic status, or other similar personal characteristics. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy toward other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Personal attacks, insulting/derogatory comments, or trolling +* Public or private harassment +* Publishing, or threatening to publish, others' private information—such as +a physical or electronic address—without explicit permission +* Other conduct which could reasonably be considered inappropriate in a +professional setting +* Advocating for or encouraging any of the above behaviors + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned with this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project email +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the Salesforce Open Source Conduct Committee +at ossconduct@salesforce.com. All complaints will be reviewed and investigated +and will result in a response that is deemed necessary and appropriate to the +circumstances. The committee is obligated to maintain confidentiality with +regard to the reporter of an incident. Further details of specific enforcement +policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership and the Salesforce Open Source Conduct +Committee. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][contributor-covenant-home], +version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html. +It includes adaptions and additions from [Go Community Code of Conduct][golang-coc], +[CNCF Code of Conduct][cncf-coc], and [Microsoft Open Source Code of Conduct][microsoft-coc]. + +This Code of Conduct is licensed under the [Creative Commons Attribution 3.0 License][cc-by-3-us]. + +[contributor-covenant-home]: https://www.contributor-covenant.org (https://www.contributor-covenant.org/) +[golang-coc]: https://golang.org/conduct +[cncf-coc]: https://github.com/cncf/foundation/blob/master/code-of-conduct.md +[microsoft-coc]: https://opensource.microsoft.com/codeofconduct/ +[cc-by-3-us]: https://creativecommons.org/licenses/by/3.0/us/ \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..9ba9791 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,14 @@ +BSD 3-Clause License + +Copyright (c) 2022 Salesforce, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README.markdown b/README.markdown index 92877d2..b72c733 100644 --- a/README.markdown +++ b/README.markdown @@ -1,3 +1,7 @@ +> [!WARNING] +> This project is deprecated, use [JSforce](https://jsforce.github.io/) instead. + + Force.com JavaScript REST Toolkit ================================= @@ -6,16 +10,51 @@ This minimal toolkit allows JavaScript in web pages to call the Force.com REST A Background ---------- -Due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), JavaScript running in Visualforce pages may not use [XmlHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) to directly invoke the REST API, since Visualforce pages have hostnames of the form abc.na1.visual.force.com, and the REST API endpoints are of the form na1.salesforce.com. +ForceTK provides a convenient, thin JavaScript abstraction of the [Force.com REST API](https://developer.salesforce.com/page/REST_API), making the API more accessible to JavaScript code running in Visualforce, in hybrid mobile apps, and elsewhere. + +Due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), JavaScript running outside the Force.com Platform may not use [XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) to directly invoke the REST API, so a minimal PHP proxy is provided. + +Recent Updates +-------------- + +* [Visualforce Remote Objects](https://www.salesforce.com/us/developer/docs/pages/index_Left.htm#CSHID=pages_remote_objects.htm|StartTopic=Content%2Fpages_remote_objects.htm|SkinName=webhelp) are proxy objects that enable basic DML operations on sObjects directly from JavaScript. Behind the scenes, the Remote Objects controller handles sharing rules, field level security, and other data accessibility concerns. Pages that use Remote Objects are subject to all the standard Visualforce limits, but like JavaScript remoting, Remote Objects calls don’t count toward API request limits. + + + Since Remote Objects are more secure than RemoteTK (which does not respect sharing rules, FLS etc since system-level access is proxied via the RemoteTK controller), and similarly do not consume API calls (the main motivation for RemoteTK), RemoteTK has been removed from the toolkit. + +* Since the Summer '13 release, the `/services/data` endpoint has been exposed on Visualforce hosts, so no proxy is now required for REST API calls in JavaScript served via Visualforce (although the proxy **is** still required for calls to `/services/apexrest`). `forcetk.js` has been updated to reflect this. + +* Inserting or updating blob data using the `create` or `update` functions (passing base64-encoded binary data in JSON) is limited by the REST API to 50 MB of text data or 37.5 MB of base64–encoded data. New functions, `createBlob` and `updateBlob`, allow creation and update of ContentVersion and Document records with binary ('blob') content with a size of up to 500 MB. Here is a minimal sample that shows how to upload a file to Chatter Files: -The RemoteTK Visualforce Custom Component (comprising RemoteTK.component and RemoteTKController.cls) provides an abstraction very similar to the REST API, implemented via `@RemoteAction` methods in the component's controller. The advantage of this mechanism is that no API calls are consumed. + +

+ Select a file to upload as a new Chatter File. +

+ +

+ + + +
-[PhoneGap](http://www.phonegap.com/) provides a way for HTML5/JavaScript apps to run as native applications; in this configuration a proxy is not required - the toolkit simply provides a convenient abstraction of the REST API. + Under the covers, `createBlob` sends a multipart message. See the REST API doc page [Insert or Update Blob Data](https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_sobject_insert_update_blob.htm) for more details. Dependencies ------------ @@ -25,37 +64,8 @@ The toolkit uses [jQuery](http://jquery.com/). It has been tested on jQuery 1.4. Configuration ------------- -RemoteTK requires no configuration. - ForceTK requires that you add the correct REST endpoint hostname for your instance (i.e. https://na1.salesforce.com/ or similar) as a remote site in *Your Name > Administration Setup > Security Controls > Remote Site Settings*. -Using RemoteTK in a Visualforce page ------------------------------------- - -Add RemoteTKController.cls and RemoteTK.component to your org by creating an Apex Class and a Component and pasting in the respective content, pasting the files into a [Force.com IDE](http://wiki.developerforce.com/page/Force.com_IDE) project, or by using the [Force.com Migration Tool](http://wiki.developerforce.com/page/Migration_Tool_Guide). - -Your Visualforce page will need to include the component and create a client object. An absolutely minimal sample is: - - - - - - -

The first account I see is .

-
- -More fully featured samples are provided in [RemoteTKExample.page](Force.com-JavaScript-REST-Toolkit/blob/master/RemoteTKExample.page) and [RemoteTKMobile.page](Force.com-JavaScript-REST-Toolkit/blob/master/RemoteTKMobile.page). - Using ForceTK in a Visualforce page ----------------------------------- @@ -67,15 +77,12 @@ Your Visualforce page will need to include jQuery and the toolkit, then create a

The first account I see is .

@@ -130,14 +137,14 @@ Your HTML page will need to include jQuery and the toolkit, then create a client function sessionCallback(oauthResponse) { if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') { - $('#message').html('Error - unauthorized!'); + $('#message').text('Error - unauthorized!'); } else { client.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); client.query("SELECT Name FROM Account LIMIT 1", function(response){ - $('#message').html('The first account I see is ' + $('#message').text('The first account I see is ' +response.records[0].Name); }); } @@ -148,39 +155,50 @@ Your HTML page will need to include jQuery and the toolkit, then create a client More fully featured samples are provided in [example.html](Force.com-JavaScript-REST-Toolkit/blob/master/example.html) and [mobile.html](Force.com-JavaScript-REST-Toolkit/blob/master/mobile.html). -Using the Toolkit in a PhoneGap app ------------------------------------ +Using the Toolkit in a Cordova app +---------------------------------- -Your HTML page will need to include jQuery, the toolkit, PhoneGap and the ChildBrowser plugin, then create a client object, passing a session ID to the constructor. You can use __https://login.salesforce.com/services/oauth2/success__ as the redirect URI and catch the page load in ChildBrowser. +Your HTML page will need to include jQuery, the toolkit and Cordova. You will also need to install the [InAppBrowser](http://plugins.cordova.io/#/package/org.apache.cordova.inappbrowser) plugin to be able to pop up a browser window for authentication. Create a client object, passing a session ID to the constructor. You can use __https://login.salesforce.com/services/oauth2/success__ as the redirect URI and catch the page load in InAppBrowser. An absolutely minimal sample using OAuth to obtain a session ID is: + - - - - - + + + -

Click here.

+ + + +

+ -A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) is provided in [phonegap.html](Force.com-JavaScript-REST-Toolkit/blob/master/phonegap.html). +A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) for iOS is provided in [cordova-ios.html](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/cordova-ios.html). The sample uses Cordova 4.3.0 and the InAppBrowser and iOS Keychain plugins. Install these with + cordova plugin add org.apache.cordova.inappbrowser + cordova plugin add com.shazron.cordova.plugin.keychainutil diff --git a/RemoteTK.component b/RemoteTK.component deleted file mode 100644 index 071114a..0000000 --- a/RemoteTK.component +++ /dev/null @@ -1,201 +0,0 @@ - - - - \ No newline at end of file diff --git a/RemoteTKController.cls b/RemoteTKController.cls deleted file mode 100644 index 7e3419e..0000000 --- a/RemoteTKController.cls +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (c) 2012, salesforce.com, inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are permitted provided - * that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this list of conditions and the - * following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and - * the following disclaimer in the documentation and/or other materials provided with the distribution. - * - * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or - * promote products derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A - * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -public class RemoteTKController { - private static String makeError(String message, String errorCode) { - JSONGenerator gen = JSON.createGenerator(false); - gen.writeStartArray(); - gen.writeStartObject(); - gen.writeStringField('message', message); - gen.writeStringField('errorCode', errorCode); - gen.writeEndObject(); - gen.writeEndArray(); - - return gen.getAsString(); - } - - private static String writeFields(String objtype, SObject obj, String fields) { - Map fieldMap = null; - try { - fieldMap = (Map)JSON.deserializeUntyped(fields); - } catch (JSONException je) { - return makeError(je.getMessage(), 'JSON_PARSER_ERROR'); - } - - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - - Map targetFields = targetType.getDescribe().fields.getMap(); - - try { - for (String key : fieldMap.keySet()) { - if (targetFields.get(key) == null) { - return '[{"message":"Field '+key+' does not exist on object type '+objtype+'","errorCode":"INVALID_FIELD"}]'; - } - - Object value = fieldMap.get(key); - Schema.DisplayType valueType = targetFields.get(key).getDescribe().getType(); - - if (value instanceof String && valueType != Schema.DisplayType.String) { - // Coerce an incoming String to the correct type - String svalue = (String)value; - - if (valueType == Schema.DisplayType.Date) { - obj.put(key, Date.valueOf(svalue)); - } else if (valueType == Schema.DisplayType.Percent || - valueType == Schema.DisplayType.Currency) { - obj.put(key, svalue == '' ? null : Decimal.valueOf(svalue)); - } else if (valueType == Schema.DisplayType.Double) { - obj.put(key, svalue == '' ? null : Double.valueOf(svalue)); - } else if (valueType == Schema.DisplayType.Integer) { - obj.put(key, Integer.valueOf(svalue)); - } else { - obj.put(key, svalue); - } - } else { - // Just try putting the incoming value on the object - obj.put(key, value); - } - } - } catch (SObjectException soe) { - return makeError(soe.getMessage(), 'INVALID_FIELD'); - } - - return null; - } - - private static List picklistOptions(Schema.DescribeFieldResult field) { - List picklistOptions = new List(); - Schema.DisplayType fieldType = field.getType(); - if (fieldType != Schema.DisplayType.Picklist && - fieldType != Schema.DisplayType.MultiPicklist && - fieldType != Schema.DisplayType.Combobox) { - return picklistOptions; - } - List picklistValues = field.getPicklistValues(); - for (Schema.PicklistEntry picklistValue: picklistValues) { - Map picklistOption = new Map(); - picklistOption.put('value', picklistValue.getValue()); - picklistOption.put('label', picklistValue.getValue()); - picklistOption.put('active', picklistValue.isActive()); - picklistOption.put('defaultValue', picklistValue.isDefaultValue()); - picklistOptions.add(picklistOption); - } - return picklistOptions; - } - - @remoteAction - public static String describe(String objtype) { - // Just enough to make the sample app work! - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - Schema.DescribeSObjectResult sobjResult = targetType.getDescribe(); - - Map fieldMap = sobjResult.fields.getMap(); - - List fields = new List(); - for (String key : fieldMap.keySet()) { - Schema.DescribeFieldResult descField = fieldMap.get(key).getDescribe(); - Map field = new Map(); - - field.put('type', descField.getType().name().toLowerCase()); - field.put('name', descField.getName()); - field.put('label', descField.getLabel()); - List references = new List(); - for (Schema.sObjectType t: descField.getReferenceTo()) { - references.add(t.getDescribe().getName()); - } - if (!references.isEmpty()) { - field.put('referenceTo', references); - } - field.put('picklistValues', picklistOptions(descField)); - - fields.add(field); - } - - Map result = new Map(); - result.put('fields', fields); - - return JSON.serialize(result); - } - - @remoteAction - public static String create(String objtype, String fields) { - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - SObject obj = targetType.newSObject(); - - String error = writeFields(objType, obj, fields); - if (error != null) { - return error; - } - - try { - insert obj; - } catch (DMLException dmle) { - String fieldNames = ''; - for (String field : dmle.getDmlFieldNames(0)) { - if (fieldNames.length() > 0) { - fieldNames += ','; - } - fieldNames += '"'+field+'"'; - } - return '[{"fields":['+fieldNames+'],"message":"'+dmle.getDmlMessage(0)+'","errorCode":"'+dmle.getDmlType(0).name()+'"}]'; - } - - Map result = new Map(); - result.put('id', obj.id); - result.put('errors', new List()); - result.put('success', true); - - return JSON.serialize(result); - } - - @remoteAction - public static String retrieve(String objtype, String id, String fieldlist) { - // TODO - handle null fieldlist - retrieve all fields - Boolean containsId = false; - for (String field : fieldlist.split(',')) { - if (field.equalsIgnoreCase('id')){ - containsId = true; - break; - } - } - - if (!containsId) { - fieldlist = 'Id,'+fieldlist; - } - - String soql = 'SELECT '+fieldlist+' FROM '+objtype+' WHERE Id = \''+id+'\''; - List records; - try { - records = Database.query(soql); - } catch (QueryException qe) { - return makeError(qe.getMessage(), 'INVALID_QUERY'); - } - - return JSON.serialize(records[0]); - } - - @remoteAction - public static String upser(String objtype, String externalIdField, String externalId, String fields) { - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - SObject obj = targetType.newSObject(); - obj.put(externalIdField, externalId); - - String error = writeFields(objType, obj, fields); - if (error != null) { - return error; - } - - Schema.SObjectField sobjField = targetType.getDescribe().fields.getMap().get(externalIdField); - - Database.Upsert(obj, sobjField); - - return null; - } - - @remoteAction - public static String updat(String objtype, String id, String fields) { - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - SObject obj = targetType.newSObject(id); - - String error = writeFields(objType, obj, fields); - if (error != null) { - return error; - } - - try { - update obj; - } catch (DMLException dmle) { - String fieldNames = ''; - for (String field : dmle.getDmlFieldNames(0)) { - if (fieldNames.length() > 0) { - fieldNames += ','; - } - fieldNames += '"'+field+'"'; - } - return '[{"fields":['+fieldNames+'],"message":"'+dmle.getDmlMessage(0)+'","errorCode":"'+dmle.getDmlType(0).name()+'"}]'; - } - - return null; - } - - @remoteAction - public static String del(String objtype, String id) { - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - SObject obj = targetType.newSObject(id); - - try { - delete obj; - } catch (DMLException dmle) { - String fieldNames = ''; - for (String field : dmle.getDmlFieldNames(0)) { - if (fieldNames.length() > 0) { - fieldNames += ','; - } - fieldNames += '"'+field+'"'; - } - return '[{"fields":['+fieldNames+'],"message":"'+dmle.getDmlMessage(0)+'","errorCode":"'+dmle.getDmlType(0).name()+'"}]'; - } - - return null; - } - - @remoteAction - public static String query(String soql) { - List records; - try { - records = Database.query(soql); - } catch (QueryException qe) { - return makeError(qe.getMessage(), 'INVALID_QUERY'); - } - - Map result = new Map(); - result.put('records', records); - result.put('totalSize', records.size()); - result.put('done', true); - - return JSON.serialize(result); - } - - @remoteAction - public static String search(String sosl) { - List> result; - try { - result = Search.query(sosl); - } catch (QueryException qe) { - return makeError(qe.getMessage(), 'INVALID_SEARCH'); - } catch (SearchException se) { - return makeError(se.getMessage(), 'INVALID_SEARCH'); - } - - return JSON.serialize(result); - } -} \ No newline at end of file diff --git a/RemoteTKExample.page b/RemoteTKExample.page deleted file mode 100644 index 2b89192..0000000 --- a/RemoteTKExample.page +++ /dev/null @@ -1,150 +0,0 @@ - - - - - - - - Force.com JavaScript REST Toolkit - - - - - - - - - - - -
-
-
-
-
-
- - - - - - - - - -
\ No newline at end of file diff --git a/RemoteTKMobile.page b/RemoteTKMobile.page deleted file mode 100644 index 25e9673..0000000 --- a/RemoteTKMobile.page +++ /dev/null @@ -1,144 +0,0 @@ - - - - -"}"/> - - - - -Accounts - - - - - - - - - - - -
- -
-

Account List

-
-
-
- -
-
    -
-
-
-

Some Text

-
-
-
-
-

Account Detail

-
-
- - - - -
Account Name:
Industry:
Ticker Symbol:
-
- - - -
-
-
-

Some Text

-
-
-
-
-

New Account

-
-
-
- - - - - - - - - - - - - - -
Account Name:
Industry:
Ticker Symbol:
- -
-
-
-

Some Text

-
-
- - -
\ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..e31774d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +## Security + +Please report any security issue to [security@salesforce.com](mailto:security@salesforce.com) +as soon as it is discovered. This library limits its runtime dependencies in +order to reduce the total cost of ownership as much as can be, but all consumers +should remain vigilant and have their security stakeholders review all third-party +products (3PP) like this one and their dependencies. \ No newline at end of file diff --git a/TestRemoteTKController.cls b/TestRemoteTKController.cls deleted file mode 100644 index daade25..0000000 --- a/TestRemoteTKController.cls +++ /dev/null @@ -1,306 +0,0 @@ -@isTest -public class TestRemoteTKController{ - private static String tooLongAccName = 'LOTS OF '+ - 'CHARACTERS XXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXX'; - - static private void assertError(String jsonResult, String expectedError, String method) { - List errorArray = (List)JSON.deserializeUntyped(jsonResult); - - System.assertNotEquals(null, errorArray, - 'error array missing from '+method+' result'); - System.assertNotEquals(0, errorArray.size(), - 'error array is empty in '+method+' result'); - - Map error = (Map)errorArray[0]; - String errorCode = (String)error.get('errorCode'); - System.assertNotEquals(null, errorCode, - 'errorCode property missing from '+method+' result'); - System.assertEquals(expectedError, errorCode, - 'errorCode should be '+expectedError+' in '+method+' result'); - } - - static testMethod void testDescribe() { - // Assume we have accounts - String jsonResult = RemoteTKController.describe('Account'); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.describe returned null'); - - Map result = (Map)JSON.deserializeUntyped(jsonResult); - - System.assertNotEquals(null, result.get('fields'), - 'fields property missing from RemoteTKController.describe result'); - - // TODO - more assertions on describe results - - // Invalid object type - // Hope there isn't a QXZXQZXZQXZQ object type! - jsonResult = RemoteTKController.describe('QXZXQZXZQXZQ'); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.describe'); - } - - static private void assertRecord(Map record, String accName, String accNumber, String method) { - Map attributes = (Map)record.get('attributes'); - System.assertNotEquals(null, attributes, - 'attributes property missing from '+method+' result'); - System.assertNotEquals(0, attributes.keySet().size(), - 'empty attributes object in '+method+' result'); - - String type = (String)attributes.get('type'); - System.assertNotEquals(null, type, - 'type property missing from '+method+' result'); - System.assertEquals('Account', type, - 'Wrong type in '+method+' result'); - - String url = (String)attributes.get('url'); - System.assertNotEquals(null, url, - 'url property missing from '+method+' result'); - - Id id = (Id)record.get('Id'); - System.assertNotEquals(null, id, - 'Id property missing from '+method+' result'); - Account account = [SELECT Id, Name FROM Account WHERE Id = :id LIMIT 1]; - System.assertNotEquals(null, account, - 'Couldn\'t find account record identified by '+method+' result'); - System.assertEquals(accName, account.Name, - 'Account name doesn\'t match in '+method+' result'); - - String name = (String)record.get('Name'); - System.assertNotEquals(null, name, - 'Name property missing from '+method+' result'); - System.assertEquals(accName, name, - 'Wrong account name in '+method+' result'); - - String accountNumber = (String)record.get('AccountNumber'); - System.assertNotEquals(null, name, - 'AccountNumber property missing from '+method+' result'); - System.assertEquals(accNumber, accountNumber, - 'Wrong account number in '+method+' result'); - } - - static private Id testCreate(String accName, String accNumber, String fields) { - // Assume we can create an account - - // Try with data in correct types - String jsonResult = RemoteTKController.create('Account', - '{"Name": "'+accName+'", '+ - '"AccountNumber" : "'+accNumber+'",'+ - fields+'}'); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.create returned null'); - - Map result = (Map)JSON.deserializeUntyped(jsonResult); - - Boolean success = (Boolean)result.get('success'); - System.assertNotEquals(null, success, - 'success property missing from RemoteTKController.create result'); - System.assertNotEquals(false, success, - 'success is false in RemoteTKController.create result'); - - List errors = (List)result.get('errors'); - System.assertNotEquals(null, errors, - 'errors property missing from RemoteTKController.create result'); - System.assertEquals(0, errors.size(), - 'errors array is not empty in RemoteTKController.create result'); - - Id id = (Id)result.get('id'); - System.assertNotEquals(null, id, - 'id property missing from RemoteTKController.create result'); - Account account = [SELECT Id, Name, AccountNumber FROM Account LIMIT 1]; - System.assertNotEquals(null, account, - 'Couldn\'t find account record created by RemoteTKController.create result'); - System.assertEquals(accName, account.Name, - 'Account name doesn\'t match in RemoteTKController.create result'); - System.assertEquals(accNumber, account.AccountNumber, - 'Account number doesn\'t match in RemoteTKController.create result'); - - jsonResult = RemoteTKController.create('QXZXQZXZQXZQ', '{"Name": "'+accName+'"}'); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.create'); - - jsonResult = RemoteTKController.create('Account', '{"Name" "'+accName+'"}'); - assertError(jsonResult, 'JSON_PARSER_ERROR', 'RemoteTKController.create'); - - jsonResult = RemoteTKController.create('Account', '{"XQZXQZXQZXQZ" : "'+accName+'"}'); - assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.create'); - - jsonResult = RemoteTKController.create('Account', '{"Name" : "'+tooLongAccName+'"}'); - assertError(jsonResult, 'STRING_TOO_LONG', 'RemoteTKController.create'); - - return id; - } - - static private void testRetrieve(String accName, String accNumber, Id id) { - String jsonResult = RemoteTKController.retrieve('Account', id, 'Name, AccountNumber'); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.retrieve returned null'); - - Map result = (Map)JSON.deserializeUntyped(jsonResult); - - assertRecord(result, accName, accNumber, 'RemoteTKController.retrieve'); - - // TODO - test negative paths for retrieve - } - - static private void testQuery(String accName, String accNumber) { - String jsonResult = RemoteTKController.query('SELECT Id, Name, AccountNumber FROM Account WHERE Name = \''+accName+'\''); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.query returned null'); - - Map result = (Map)JSON.deserializeUntyped(jsonResult); - - List records = (List)result.get('records'); - System.assertNotEquals(null, records, - 'records property missing from RemoteTKController.query result'); - System.assertEquals(1, records.size(), - 'records array should have single record in RemoteTKController.query result'); - - Map record = (Map)records[0]; - - assertRecord(record, accName, accNumber, 'RemoteTKController.query'); - - Integer totalSize = (Integer)result.get('totalSize'); - System.assertNotEquals(null, totalSize, - 'totalSize property missing from RemoteTKController.query result'); - System.assertEquals(1, totalSize, - 'totalSize should be 1 in RemoteTKController.query result'); - - Boolean done = (Boolean)result.get('done'); - System.assertNotEquals(null, done, - 'done property missing from RemoteTKController.query result'); - System.assertEquals(true, done, - 'done should be true in RemoteTKController.query result'); - - jsonResult = RemoteTKController.query('SSSSSS Id, Name FROM Account WHERE Name = \''+accName+'\''); - assertError(jsonResult, 'INVALID_QUERY', 'RemoteTKController.query'); - } - - static private void testSearch(String accName, String accNumber, Id id) { - Id [] fixedSearchResults= new Id[1]; - fixedSearchResults[0] = id; - Test.setFixedSearchResults(fixedSearchResults); - String jsonResult = RemoteTKController.search('FIND {'+accName+'} IN ALL FIELDS RETURNING Account (Id, Name, AccountNumber)'); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.search returned null'); - - List result = (List)JSON.deserializeUntyped(jsonResult); - - List records = (List)result[0]; - - Map record = (Map)records[0]; - - assertRecord(record, accName, accNumber, 'RemoteTKController.search'); - - jsonResult = RemoteTKController.search('FFFF {'+accName+'} IN ALL FIELDS RETURNING Account (Id, Name)'); - assertError(jsonResult, 'INVALID_SEARCH', 'RemoteTKController.search'); - } - - static private void testUpdate(String accName, String accNumber, Id id, String fields) { - String jsonResult = RemoteTKController.updat('Account', id, '{"Name":"'+accName+'", "AccountNumber":"'+accNumber+'"}'); - System.assertEquals(null, jsonResult, - 'Non-null result from RemoteTKController.updat'); - Account account = [SELECT Id, Name, AccountNumber FROM Account WHERE Id = :id LIMIT 1]; - System.assertNotEquals(null, account, - 'Couldn\'t find account record after RemoteTKController.updat'); - System.assertEquals(accName, account.Name, - 'Account name doesn\'t match after RemoteTKController.updat'); - System.assertEquals(accNumber, account.AccountNumber, - 'Account number doesn\'t match after RemoteTKController.updat'); - - jsonResult = RemoteTKController.updat('QXZXQZXZQXZQ', id, '{"Name":"'+accName+'"}'); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.updat'); - - jsonResult = RemoteTKController.updat('Account', id, '{"XQZXQZXQZXQZ" : "'+accName+'"}'); - assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.updat'); - - jsonResult = RemoteTKController.updat('Account', id, '{"Name" "'+accName+'"}'); - assertError(jsonResult, 'JSON_PARSER_ERROR', 'RemoteTKController.updat'); - - jsonResult = RemoteTKController.updat('Account', id, '{"Name" : "'+tooLongAccName+'"}'); - assertError(jsonResult, 'STRING_TOO_LONG', 'RemoteTKController.updat'); - } - - static private void testUpsert(String accName, String accNumber, Id id, String fields) { - String jsonResult = RemoteTKController.upser('Account', - 'Id', - (String)id, - '{"Name":"'+accName+'", '+ - '"AccountNumber":"'+accNumber+'",'+ - fields+'}'); - System.assertEquals(null, jsonResult, - 'Non-null result from RemoteTKController.upser'); - Account account = [SELECT Id, Name, AccountNumber FROM Account WHERE Id = :id LIMIT 1]; - System.assertNotEquals(null, account, - 'Couldn\'t find account record after RemoteTKController.upser'); - System.assertEquals(accName, account.Name, - 'Account name doesn\'t match after RemoteTKController.upser'); - System.assertEquals(accNumber, account.AccountNumber, - 'Account number doesn\'t match after RemoteTKController.upser'); - - jsonResult = RemoteTKController.upser('QXZXQZXZQXZQ', 'Id', (String)id, '{"Name":"'+accName+'"}'); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.upser'); - - jsonResult = RemoteTKController.upser('Account', 'Id', (String)id, '{"XQZXQZXQZXQZ" : "'+accName+'"}'); - assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.upser'); - } - - static private void testDelete(Id id) { - String jsonResult = RemoteTKController.del('QXZXQZXZQXZQ', id); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.del'); - - jsonResult = RemoteTKController.del('Account', id); - System.assertEquals(null, jsonResult, - 'Non-null result from RemoteTKController.del'); - List accounts = [SELECT Id, Name FROM Account WHERE Id = :id]; - System.assertEquals(0, accounts.size(), - 'Account record was not deleted by RemoteTKController.del'); - - jsonResult = RemoteTKController.del('Account', id); - assertError(jsonResult, 'ENTITY_IS_DELETED', 'RemoteTKController.del'); - } - - static testMethod void testCRUD() { - String accName = 'Test1'; - String accNumber = '1234'; - - // String field values - Id id = testCreate(accName, accNumber, '"AnnualRevenue" : "1000000",'+ - '"NumberOfEmployees" : "1000",'+ - '"Phone" : "(111) 222-3333"'); - testDelete(id); - - // Integer field values - id = testCreate(accName, accNumber, '"AnnualRevenue" : 1000000,'+ - '"NumberOfEmployees" : 1000,'+ - '"Phone" : "(111) 222-3333"'); - testRetrieve(accName, accNumber, id); - testQuery(accName, accNumber); - testSearch(accName, accNumber, id); - testUpdate(accName+'1', accNumber+'1', id, '"AnnualRevenue" : "1100000",'+ - '"NumberOfEmployees" : "1100",'+ - '"Phone" : "(112) 222-3333"'); - testUpdate(accName+'2', accNumber+'2', id, '"AnnualRevenue" : "2000000",'+ - '"NumberOfEmployees" : "2000",'+ - '"Phone" : "(222) 222-3333"'); - testUpsert(accName+'3', accNumber+'3', id, '"AnnualRevenue" : 3000000,'+ - '"NumberOfEmployees" : 3000,'+ - '"Phone" : "(333) 222-3333"'); - testUpsert(accName+'4', accNumber+'4', id, '"AnnualRevenue" : 4000000,'+ - '"NumberOfEmployees" : 4000,'+ - '"Phone" : "(444) 222-3333"'); - testDelete(id); - } -} \ No newline at end of file diff --git a/app.js b/app.js index 10b7064..7ce5297 100644 --- a/app.js +++ b/app.js @@ -51,18 +51,18 @@ function metadataCallback(response){ // Using TrimPath Template for now - may switch to jQuery Template at some // point - $j('#prompt').html(TrimPath.processDOMTemplate("prompt_jst" + $('#prompt').html(TrimPath.processDOMTemplate("prompt_jst" , response)); // Set up autocomplete - $j( "#value" ).autocomplete({ + $( "#value" ).autocomplete({ source: function( request, response ) { var query = "SELECT Id, Name FROM Account "+ - "WHERE "+$j("#field").val()+" LIKE '%"+request.term+"%' "+ + "WHERE "+$("#field").val()+" LIKE '%"+request.term+"%' "+ "ORDER BY Name LIMIT 20"; client.query(query, function( data ) { - response( $j.map( data.records, function( record ) { + response( $.map( data.records, function( record ) { return { label: record.Name, value: record.Id @@ -76,22 +76,22 @@ if ( ui.item != null ) { showAccountDetail(ui.item.value); } else { - filterAccounts($j("#field").val(),this.value); + filterAccounts($("#field").val(),this.value); } return false; }, }); - $j('#go').click(function(e) { - var field = $j("#field").val(); - var value = $j("#value").val(); + $('#go').click(function(e) { + var field = $("#field").val(); + var value = $("#value").val(); e.preventDefault(); filterAccounts(field,value); }); - $j('#new').click(function(e) { + $('#new').click(function(e) { e.preventDefault(); // Just make Trimpath happy @@ -101,19 +101,19 @@ dummy[response.fields[i].name] = ''; } $dialog.html(TrimPath.processDOMTemplate("edit_jst", dummy)); - $dialog.find('#action').html('Create').click(function(e) { + $dialog.find('#action').text('Create').click(function(e) { e.preventDefault(); $dialog.dialog('close'); var fields = {}; $dialog.find('input').each(function() { - var child = $j(this); + var child = $(this); if ( child.val().length > 0 ) { fields[child.attr("name")] = child.val(); } }); - $j('#list').html(ajaxgif+" creating account..."); + $('#list').html(ajaxgif+" creating account..."); client.create('Account', fields, createCallback, errorCallback); }); @@ -125,21 +125,21 @@ } function queryCallback(response) { - $j('#list').html(TrimPath.processDOMTemplate("accounts_jst" + $('#list').html(TrimPath.processDOMTemplate("accounts_jst" , response)); - $j('#version').html($j.fn.jquery); - $j('#uiversion').html($j.ui.version); + $('#version').text($.fn.jquery); + $('#uiversion').text($.ui.version); - $j("#list tr:nth-child(odd)").addClass("odd"); + $("#list tr:nth-child(odd)").addClass("odd"); - $j('#logout').click(logout); + $('#logout').click(logout); - $j('#accounts').find('.id') + $('#accounts').find('.id') .hover(function() { - $j(this).addClass("highlighted"); + $(this).addClass("highlighted"); },function(){ - $j(this).removeClass("highlighted"); + $(this).removeClass("highlighted"); }) .click(function(){ showAccountDetail(this.id); @@ -156,36 +156,36 @@ && !response.Website.startsWith('http://')) { response.Website = 'http://'+response.Website; } - $dialog.html(TrimPath.processDOMTemplate("detail_jst" + $dialog.TrimPath.processDOMTemplate("detail_jst" ,response)); $dialog.find('#industry').click(function(e) { e.preventDefault(); $dialog.dialog('close'); - filterIndustry($j(this).html()); + filterIndustry($(this).text()); }); $dialog.find('#delete').click(function(e) { e.preventDefault(); $dialog.dialog('close'); - $j('#list').html(ajaxgif+" deleting account..."); + $('#list').html(ajaxgif+" deleting account..."); client.del('Account', $dialog.find('#id').val(), deleteCallback, errorCallback); }); $dialog.find('#edit').click(function(e) { e.preventDefault(); $dialog.html(TrimPath.processDOMTemplate("edit_jst" ,response)); - $dialog.find('#action').html('Update').click(function(e) { + $dialog.find('#action').text('Update').click(function(e) { e.preventDefault(); $dialog.dialog('close'); var fields = {}; $dialog.find('input').each(function() { - var child = $j(this); + var child = $(this); if ( child.val().length > 0 && child.attr("name") != 'id') { fields[child.attr("name")] = child.val(); } }); - $j('#list').html(ajaxgif+" updating account..."); + $('#list').html(ajaxgif+" updating account..."); client.update('Account', $dialog.find('#id').val(), fields, updateCallback, errorCallback); }); @@ -193,19 +193,19 @@ } function createCallback(response) { - $j('#list').html('Created '+response.id); + $('#list').text('Created '+response.id); setTimeout("filterAccounts()",1000); } function updateCallback(response) { - $j('#list').html('Updated'); + $('#list').text('Updated'); setTimeout("filterAccounts()",1000); } function deleteCallback(response) { - $j('#list').html('Deleted'); + $('#list').text('Deleted'); setTimeout("filterAccounts()",1000); } @@ -222,7 +222,7 @@ } function filterIndustry(industry) { - $j('#list').html(ajaxgif+" loading data..."); + $('#list').html(ajaxgif+" loading data..."); var query = "SELECT Id, Name FROM Account WHERE Industry = '"+industry +"' ORDER BY Name LIMIT 20"; @@ -231,7 +231,7 @@ } function filterAccounts(field, value) { - $j('#list').html(ajaxgif+" loading data..."); + $('#list').html(ajaxgif+" loading data..."); var query = ( typeof value !== 'undefined' && value.length > 0 ) ? "SELECT Id, Name FROM Account WHERE "+field+" LIKE '%"+value diff --git a/bulk.page b/bulk.page new file mode 100644 index 0000000..e9e7504 --- /dev/null +++ b/bulk.page @@ -0,0 +1,255 @@ + + + + +
+

1. Create a Bulk API job


+ + +
+ + +
+ + + +
+
+

+    
+ + + + + + + + +
\ No newline at end of file diff --git a/bulktk.js b/bulktk.js new file mode 100644 index 0000000..4540aea --- /dev/null +++ b/bulktk.js @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2015, salesforce.com, inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or + * promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * BulkTK: JavaScript library to wrap Force.com Bulk API. Extends ForceTK. + * Dependencies: + * jquery - http://jquery.com/ + * ForceTK - https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/forcetk.js + * jxon - https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/jxon.js + * (originally from the [Ratatosk](https://github.com/wireload/Ratatosk) + * project; this version preserves case in element and attribute names) + */ + +forcetk.Client.prototype.xmlHeader = "\n"; + +/* + * Low level utility function to call the Bulk API. + * @param path resource path + * @param parseXML set to true to parse XML response + * @param callback function to which response will be passed + * @param [error=null] function to which jqXHR will be passed in case of error + * @param [method="GET"] HTTP method for call + * @param [contentType=null] Content type of payload - e.g. 'application/xml; charset=UTF-8' + * @param [payload=null] payload for POST + * @param [parseXML=false] set to true to parse XML response + */ +forcetk.Client.prototype.bulkAjax = function(path, parseXML, callback, error, method, contentType, payload, retry) { + var that = this; + var url = this.instanceUrl + path; + + if (this.debug) { + console.log('bulkAjax sending: ', payload); + } + + return $.ajax({ + type: method || "GET", + async: this.asyncAjax, + url: (this.proxyUrl !== null) ? this.proxyUrl: url, + contentType: method == "DELETE" ? null : contentType, + cache: false, + processData: false, + data: payload, + success: function(data, textStatus, jqXHR) { + var respContentType = jqXHR.getResponseHeader('Content-Type'); + // Naughty Bulk API doesn't always set Content-Type! + if (parseXML && + ((respContentType && respContentType.indexOf('application/xml') === 0) || + data.indexOf(' + + + + + Accounts + + + + + + + + + + + + +
+
+

Login

+
+
+ Connecting to Force.com +
+
+

Force.com

+
+
+
+
+

Account List

+
+
+
+ +
+
    +
+
+ +
+
+
+

Force.com

+
+
+
+
+

Account Detail

+
+
+ + + + +
Account Name:
Industry:
Ticker Symbol:
+
+ + + +
+
+
+

Force.com

+
+
+
+
+

New Account

+
+
+
+ + + + + + + + + + + + + + +
Account Name:
Industry:
Ticker Symbol:
+ +
+
+
+

Force.com

+
+
+ + diff --git a/example.html b/example.html index 1af86b9..f5439d4 100644 --- a/example.html +++ b/example.html @@ -76,13 +76,8 @@ var $dialog = null; - // We use $j rather than $ for jQuery - if (window.$j === undefined) { - $j = $; - } - - $j(document).ready(function() { - $j('#login').popupWindow({ + $(document).ready(function() { + $('#login').popupWindow({ windowURL: getAuthorizeUrl(loginUrl, clientId, redirectUri), windowName: 'Connect', centerBrowser: 1, @@ -90,7 +85,7 @@ width:675 }); - $dialog = $j('
') + $dialog = $('
') .dialog({ autoOpen: false, width: 450 @@ -104,13 +99,12 @@ } function hideButton(){ - $j('#connect').html(ajaxgif+" connecting..."); + $('#connect').text(ajaxgif+" connecting..."); } function sessionCallback(oauthResponse) { if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') { - //$j('#prompt').html('Error - unauthorized!'); errorCallback({ status: 0, statusText: 'Unauthorized', @@ -121,7 +115,7 @@ oauthResponse.instance_url); // Kick things off by doing a describe on Account... - $j('#prompt').html(ajaxgif+" loading metadata..."); + $('#prompt').text(ajaxgif+" loading metadata..."); client.describe('Account',metadataCallback, errorCallback); } } diff --git a/example.page b/example.page index e18b827..7ce51a7 100644 --- a/example.page +++ b/example.page @@ -48,9 +48,6 @@ Sample Visualforce page for Force.com JavaScript REST Toolkit * It must go in the VF page so that merge variables are processed. */ - // Get a reference to jQuery that we can work with - $j = jQuery.noConflict(); - // Get an instance of the REST API client and set the session ID var client = new forcetk.Client(); client.setSessionToken('{!$Api.Session_ID}'); @@ -59,16 +56,16 @@ Sample Visualforce page for Force.com JavaScript REST Toolkit var $dialog = null; - $j(document).ready(function() { + $(document).ready(function() { // Set up the dialog - $dialog = $j('
') + $dialog = $('
') .dialog({ autoOpen: false, width: 450 }); // Kick things off by doing a describe on Account... - $j('#prompt').html(ajaxgif+" loading metadata..."); + $('#prompt').html(ajaxgif+" loading metadata..."); client.describe('Account', metadataCallback); }); diff --git a/forcetk.js b/forcetk.js index b6d37fe..7fd2918 100644 --- a/forcetk.js +++ b/forcetk.js @@ -32,6 +32,9 @@ * console, go to Your Name | Setup | Security Controls | Remote Site Settings */ +/*jslint browser: true*/ +/*global alert, Blob, $, jQuery*/ + var forcetk = window.forcetk; if (forcetk === undefined) { @@ -40,11 +43,6 @@ if (forcetk === undefined) { if (forcetk.Client === undefined) { - // We use $j rather than $ for jQuery so it works in Visualforce - if (window.$j === undefined) { - $j = $; - } - /** * The Client provides a convenient wrapper for the Force.com REST API, * allowing JavaScript in Visualforce pages to use the API via the Ajax @@ -55,15 +53,16 @@ if (forcetk.Client === undefined) { * PhoneGap etc * @constructor */ - forcetk.Client = function(clientId, loginUrl, proxyUrl) { + forcetk.Client = function (clientId, loginUrl, proxyUrl) { + 'use strict'; this.clientId = clientId; this.loginUrl = loginUrl || 'https://login.salesforce.com/'; - if (typeof proxyUrl === 'undefined' || proxyUrl === null) { + if (proxyUrl === undefined || proxyUrl === null) { if (location.protocol === 'file:' || location.protocol === 'ms-appx:') { // In PhoneGap this.proxyUrl = null; } else { - // In Visualforce + // In Visualforce - still need proxyUrl for Apex REST methods this.proxyUrl = location.protocol + "//" + location.hostname + "/services/proxy"; } @@ -76,75 +75,80 @@ if (forcetk.Client === undefined) { this.refreshToken = null; this.sessionId = null; this.apiVersion = null; + this.visualforce = false; this.instanceUrl = null; this.asyncAjax = true; - } + }; /** * Set a refresh token in the client. * @param refreshToken an OAuth refresh token */ - forcetk.Client.prototype.setRefreshToken = function(refreshToken) { + forcetk.Client.prototype.setRefreshToken = function (refreshToken) { + 'use strict'; this.refreshToken = refreshToken; - } + }; /** * Refresh the access token. * @param callback function to call on success * @param error function to call on failure */ - forcetk.Client.prototype.refreshAccessToken = function(callback, error) { - var that = this; - var url = this.loginUrl + '/services/oauth2/token'; - return $j.ajax({ + forcetk.Client.prototype.refreshAccessToken = function (callback, error) { + 'use strict'; + var that = this, + url = this.loginUrl + '/services/oauth2/token'; + return $.ajax({ type: 'POST', - url: (this.proxyUrl !== null) ? this.proxyUrl: url, + url: (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, cache: false, processData: false, data: 'grant_type=refresh_token&client_id=' + this.clientId + '&refresh_token=' + this.refreshToken, success: callback, error: error, dataType: "json", - beforeSend: function(xhr) { - if (that.proxyUrl !== null) { + beforeSend: function (xhr) { + if (that.proxyUrl !== null && !this.visualforce) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } } }); - } + }; /** * Set a session token and the associated metadata in the client. * @param sessionId a salesforce.com session ID. In a Visualforce page, * use '{!$Api.sessionId}' to obtain a session ID. - * @param [apiVersion="21.0"] Force.com API version + * @param [apiVersion="v29.0"] Force.com API version * @param [instanceUrl] Omit this if running on Visualforce; otherwise * use the value from the OAuth token. */ - forcetk.Client.prototype.setSessionToken = function(sessionId, apiVersion, instanceUrl) { + forcetk.Client.prototype.setSessionToken = function (sessionId, apiVersion, instanceUrl) { + 'use strict'; this.sessionId = sessionId; - this.apiVersion = (typeof apiVersion === 'undefined' || apiVersion === null) - ? 'v27.0': apiVersion; - if (typeof instanceUrl === 'undefined' || instanceUrl == null) { + this.apiVersion = (apiVersion === undefined || apiVersion === null) + ? 'v29.0' : apiVersion; + if (instanceUrl === undefined || instanceUrl === null) { + this.visualforce = true; + // location.hostname can be of the form 'abc.na1.visual.force.com', // 'na1.salesforce.com' or 'abc.my.salesforce.com' (custom domains). // Split on '.', and take the [1] or [0] element as appropriate - var elements = location.hostname.split("."); - - var instance = null; - if(elements.length == 4 && elements[1] === 'my') { + var elements = location.hostname.split("."), + instance = null; + if (elements.length === 4 && elements[1] === 'my') { instance = elements[0] + '.' + elements[1]; - } else if(elements.length == 3){ + } else if (elements.length === 3) { instance = elements[0]; } else { instance = elements[1]; } - + this.instanceUrl = "https://" + instance + ".salesforce.com"; } else { this.instanceUrl = instanceUrl; } - } + }; /* * Low level utility function to call the Salesforce endpoint. @@ -154,41 +158,42 @@ if (forcetk.Client === undefined) { * @param [method="GET"] HTTP method for call * @param [payload=null] payload for POST/PATCH etc */ - forcetk.Client.prototype.ajax = function(path, callback, error, method, payload, retry) { - var that = this; - var url = this.instanceUrl + '/services/data' + path; + forcetk.Client.prototype.ajax = function (path, callback, error, method, payload, retry) { + 'use strict'; + var that = this, + url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path; - return $j.ajax({ + return $.ajax({ type: method || "GET", async: this.asyncAjax, - url: (this.proxyUrl !== null) ? this.proxyUrl: url, - contentType: method == "DELETE" ? null : 'application/json', + url: (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, + contentType: method === "DELETE" ? null : 'application/json', cache: false, processData: false, data: payload, success: callback, - error: (!this.refreshToken || retry ) ? error : function(jqXHR, textStatus, errorThrown) { + error: (!this.refreshToken || retry) ? error : function (jqXHR, textStatus, errorThrown) { if (jqXHR.status === 401) { - that.refreshAccessToken(function(oauthResponse) { + that.refreshAccessToken(function (oauthResponse) { that.setSessionToken(oauthResponse.access_token, null, - oauthResponse.instance_url); + oauthResponse.instance_url); that.ajax(path, callback, error, method, payload, true); }, - error); + error); } else { error(jqXHR, textStatus, errorThrown); } }, dataType: "json", - beforeSend: function(xhr) { - if (that.proxyUrl !== null) { + beforeSend: function (xhr) { + if (that.proxyUrl !== null && !that.visualforce) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } - xhr.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); + xhr.setRequestHeader(that.authzHeader, "Bearer " + that.sessionId); xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); } }); - } + }; /** * Utility function to query the Chatter API and download a file @@ -200,56 +205,174 @@ if (forcetk.Client === undefined) { * @param mimetype of the file * @param callback function to which response will be passed * @param [error=null] function to which request will be passed in case of error - * @param rety true if we've already tried refresh token flow once - **/ - forcetk.Client.prototype.getChatterFile = function(path,mimeType,callback,error,retry) { - var that = this; - var url = this.instanceUrl + path; - - var request = new XMLHttpRequest(); - - request.open("GET", (this.proxyUrl !== null) ? this.proxyUrl: url, true); + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.getChatterFile = function (path, mimeType, callback, error, retry) { + 'use strict'; + var that = this, + url = (this.visualforce ? '' : this.instanceUrl) + path, + request = new XMLHttpRequest(); + + request.open("GET", (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, true); request.responseType = "arraybuffer"; - - request.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); - request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); - if (this.proxyUrl !== null) { + + request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); + request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); + if (this.proxyUrl !== null && !this.visualforce) { request.setRequestHeader('SalesforceProxy-Endpoint', url); } - - request.onreadystatechange = function() { + + request.onreadystatechange = function () { // continue if the process is completed - if (request.readyState == 4) { + if (request.readyState === 4) { // continue only if HTTP status is "OK" - if (request.status == 200) { + if (request.status === 200) { try { // retrieve the response callback(request.response); - } - catch(e) { + } catch (e) { // display error message alert("Error reading the response: " + e.toString()); } - } - //refresh token in 401 - else if(request.status == 401 && !retry) { - that.refreshAccessToken(function(oauthResponse) { - that.setSessionToken(oauthResponse.access_token, null,oauthResponse.instance_url); + } else if (request.status === 401 && !retry) { + //refresh token in 401 + that.refreshAccessToken(function (oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); that.getChatterFile(path, mimeType, callback, error, true); - }, - error); - } - else { + }, error); + } else { // display status message - error(request,request.statusText,request.response); + error(request, request.statusText, request.response); } - } - - } + } + }; request.send(); - - } + + }; + + // Local utility to create a random string for multipart boundary + var randomString = function () { + 'use strict'; + var str = '', + i; + for (i = 0; i < 4; i += 1) { + str += (Math.random().toString(16) + "000000000").substr(2, 8); + } + return str; + }; + + /* Low level function to create/update records with blob data + * @param path resource path relative to /services/data + * @param fields an object containing initial field names and values for + * the record, e.g. {ContentDocumentId: "069D00000000so2", + * PathOnClient: "Q1 Sales Brochure.pdf"} + * @param filename filename for blob data; e.g. "Q1 Sales Brochure.pdf" + * @param payloadField 'VersionData' for ContentVersion, 'Body' for Document + * @param payload Blob, File, ArrayBuffer (Typed Array), or String payload + * @param callback function to which response will be passed + * @param [error=null] function to which response will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.blob = function (path, fields, filename, payloadField, payload, callback, error, retry) { + 'use strict'; + var that = this, + url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path, + boundary = randomString(), + blob = new Blob([ + "--boundary_" + boundary + '\n' + + "Content-Disposition: form-data; name=\"entity_content\";" + "\n" + + "Content-Type: application/json" + "\n\n" + + JSON.stringify(fields) + + "\n\n" + + "--boundary_" + boundary + "\n" + + "Content-Type: application/octet-stream" + "\n" + + "Content-Disposition: form-data; name=\"" + payloadField + + "\"; filename=\"" + filename + "\"\n\n", + payload, + "\n\n" + + "--boundary_" + boundary + "--" + ], {type : 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'}), + request = new XMLHttpRequest(); + + request.open("POST", (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, this.asyncAjax); + + request.setRequestHeader('Accept', 'application/json'); + request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); + request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); + request.setRequestHeader('Content-Type', 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'); + if (this.proxyUrl !== null && !this.visualforce) { + request.setRequestHeader('SalesforceProxy-Endpoint', url); + } + + if (this.asyncAjax) { + request.onreadystatechange = function () { + // continue if the process is completed + if (request.readyState === 4) { + // continue only if HTTP status is good + if (request.status >= 200 && request.status < 300) { + // retrieve the response + callback(request.response ? JSON.parse(request.response) : null); + } else if (request.status === 401 && !retry) { + that.refreshAccessToken(function (oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); + that.blob(path, fields, filename, payloadField, payload, callback, error, true); + }, error); + } else { + // return status message + error(request, request.statusText, request.response); + } + } + }; + } + + request.send(blob); + + return this.asyncAjax ? null : JSON.parse(request.response); + }; + + /* + * Create a record with blob data + * @param objtype object type; e.g. "ContentVersion" + * @param fields an object containing initial field names and values for + * the record, e.g. {ContentDocumentId: "069D00000000so2", + * PathOnClient: "Q1 Sales Brochure.pdf"} + * @param filename filename for blob data; e.g. "Q1 Sales Brochure.pdf" + * @param payloadField 'VersionData' for ContentVersion, 'Body' for Document + * @param payload Blob, File, ArrayBuffer (Typed Array), or String payload + * @param callback function to which response will be passed + * @param [error=null] function to which response will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.createBlob = function (objtype, fields, filename, + payloadField, payload, callback, + error, retry) { + 'use strict'; + return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/', + fields, filename, payloadField, payload, callback, error, retry); + }; + + /* + * Update a record with blob data + * @param objtype object type; e.g. "ContentVersion" + * @param id the record's object ID + * @param fields an object containing initial field names and values for + * the record, e.g. {ContentDocumentId: "069D00000000so2", + * PathOnClient: "Q1 Sales Brochure.pdf"} + * @param filename filename for blob data; e.g. "Q1 Sales Brochure.pdf" + * @param payloadField 'VersionData' for ContentVersion, 'Body' for Document + * @param payload Blob, File, ArrayBuffer (Typed Array), or String payload + * @param callback function to which response will be passed + * @param [error=null] function to which response will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.updateBlob = function (objtype, id, fields, filename, + payloadField, payload, callback, + error, retry) { + 'use strict'; + return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + + '?_HttpMethod=PATCH', fields, filename, payloadField, payload, callback, error, retry); + }; /* * Low level utility function to call the Salesforce endpoint specific for Apex REST API. @@ -257,52 +380,73 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error * @param [method="GET"] HTTP method for call - * @param [payload=null] payload for POST/PATCH etc - * @param [paramMap={}] parameters to send as header values for POST/PATCH etc - * @param [retry] specifies whether to retry on error + * @param [payload=null] string or object with payload for POST/PATCH etc or params for GET + * @param [paramMap={}] parameters to send as header values for POST/PATCH etc + * @param [retry] specifies whether to retry on error */ - forcetk.Client.prototype.apexrest = function(path, callback, error, method, payload, paramMap, retry) { - var that = this; - var url = this.instanceUrl + '/services/apexrest' + path; + forcetk.Client.prototype.apexrest = function (path, callback, error, method, payload, paramMap, retry) { + 'use strict'; + var that = this, + url = this.instanceUrl + '/services/apexrest' + path; - return $j.ajax({ - type: method || "GET", + method = method || "GET"; + + if (method === "GET") { + // Handle proxied query params correctly + if (this.proxyUrl && payload) { + if (typeof payload !== 'string') { + payload = $.param(payload); + } + url += "?" + payload; + payload = null; + } + } else { + // Allow object payload for POST etc + if (payload && typeof payload !== 'string') { + payload = JSON.stringify(payload); + } + } + + return $.ajax({ + type: method, async: this.asyncAjax, - url: (this.proxyUrl !== null) ? this.proxyUrl: url, + url: this.proxyUrl || url, contentType: 'application/json', cache: false, processData: false, data: payload, success: callback, - error: (!this.refreshToken || retry ) ? error : function(jqXHR, textStatus, errorThrown) { + error: (!this.refreshToken || retry) ? error : function (jqXHR, textStatus, errorThrown) { if (jqXHR.status === 401) { - that.refreshAccessToken(function(oauthResponse) { + that.refreshAccessToken(function (oauthResponse) { that.setSessionToken(oauthResponse.access_token, null, - oauthResponse.instance_url); + oauthResponse.instance_url); that.apexrest(path, callback, error, method, payload, paramMap, true); - }, - error); + }, error); } else { error(jqXHR, textStatus, errorThrown); } }, dataType: "json", - beforeSend: function(xhr) { + beforeSend: function (xhr) { + var paramName; if (that.proxyUrl !== null) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } - //Add any custom headers - if (paramMap === null) { - paramMap = {}; - } - for (paramName in paramMap) { - xhr.setRequestHeader(paramName, paramMap[paramName]); - } - xhr.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); + //Add any custom headers + if (paramMap === null) { + paramMap = {}; + } + for (paramName in paramMap) { + if (paramMap.hasOwnProperty(paramName)) { + xhr.setRequestHeader(paramName, paramMap[paramName]); + } + } + xhr.setRequestHeader(that.authzHeader, "Bearer " + that.sessionId); xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); } }); - } + }; /* * Lists summary information about each Salesforce.com version currently @@ -311,9 +455,10 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.versions = function(callback, error) { + forcetk.Client.prototype.versions = function (callback, error) { + 'use strict'; return this.ajax('/', callback, error); - } + }; /* * Lists available resources for the client's API version, including @@ -321,9 +466,10 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.resources = function(callback, error) { + forcetk.Client.prototype.resources = function (callback, error) { + 'use strict'; return this.ajax('/' + this.apiVersion + '/', callback, error); - } + }; /* * Lists the available objects and their metadata for your organization's @@ -331,9 +477,10 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.describeGlobal = function(callback, error) { + forcetk.Client.prototype.describeGlobal = function (callback, error) { + 'use strict'; return this.ajax('/' + this.apiVersion + '/sobjects/', callback, error); - } + }; /* * Describes the individual metadata for the specified object. @@ -341,10 +488,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.metadata = function(objtype, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' - , callback, error); - } + forcetk.Client.prototype.metadata = function (objtype, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/', + callback, error); + }; /* * Completely describes the individual metadata at all levels for the @@ -353,10 +501,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.describe = function(objtype, callback, error) { + forcetk.Client.prototype.describe = function (objtype, callback, error) { + 'use strict'; return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype - + '/describe/', callback, error); - } + + '/describe/', callback, error); + }; /* * Creates a new record of the given type. @@ -367,10 +516,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.create = function(objtype, fields, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' - , callback, error, "POST", JSON.stringify(fields)); - } + forcetk.Client.prototype.create = function (objtype, fields, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/', + callback, error, "POST", JSON.stringify(fields)); + }; /* * Retrieves field values for a record of the given type. @@ -381,16 +531,17 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.retrieve = function(objtype, id, fieldlist, callback, error) { - if (arguments.length == 4) { + forcetk.Client.prototype.retrieve = function (objtype, id, fieldlist, callback, error) { + 'use strict'; + if (arguments.length === 4) { error = callback; callback = fieldlist; fieldlist = null; } var fields = fieldlist ? '?fields=' + fieldlist : ''; - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id - + fields, callback, error); - } + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + + fields, callback, error); + }; /* * Upsert - creates or updates record of the given type, based on the @@ -404,10 +555,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.upsert = function(objtype, externalIdField, externalId, fields, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + externalIdField + '/' + externalId - + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); - } + forcetk.Client.prototype.upsert = function (objtype, externalIdField, externalId, fields, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + externalIdField + '/' + externalId + + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); + }; /* * Updates field values on a record of the given type. @@ -419,10 +571,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.update = function(objtype, id, fields, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id - + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); - } + forcetk.Client.prototype.update = function (objtype, id, fields, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); + }; /* * Deletes a record of the given type. Unfortunately, 'delete' is a @@ -432,10 +585,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.del = function(objtype, id, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id - , callback, error, "DELETE"); - } + forcetk.Client.prototype.del = function (objtype, id, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id, + callback, error, "DELETE"); + }; /* * Executes the specified SOQL query. @@ -444,11 +598,12 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.query = function(soql, callback, error) { - return this.ajax('/' + this.apiVersion + '/query?q=' + escape(soql) - , callback, error); - } - + forcetk.Client.prototype.query = function (soql, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/query?q=' + encodeURIComponent(soql), + callback, error); + }; + /* * Queries the next set of records based on pagination. *

This should be used if performing a query that retrieves more than can be returned @@ -459,19 +614,18 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.queryMore = function( url, callback, error ){ + forcetk.Client.prototype.queryMore = function (url, callback, error) { + 'use strict'; //-- ajax call adds on services/data to the url call, so only send the url after - var serviceData = "services/data"; - var index = url.indexOf( serviceData ); - - if( index > -1 ){ - url = url.substr( index + serviceData.length ); - } else { - //-- leave alone + var serviceData = "services/data", + index = url.indexOf(serviceData); + + if (index > -1) { + url = url.substr(index + serviceData.length); } - - return this.ajax( url, callback, error ); - } + + return this.ajax(url, callback, error); + }; /* * Executes the specified SOSL search. @@ -480,8 +634,9 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.search = function(sosl, callback, error) { - return this.ajax('/' + this.apiVersion + '/search?q=' + escape(sosl) - , callback, error); - } + forcetk.Client.prototype.search = function (sosl, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/search?q=' + encodeURIComponent(sosl), + callback, error); + }; } diff --git a/jxon.js b/jxon.js new file mode 100644 index 0000000..192694d --- /dev/null +++ b/jxon.js @@ -0,0 +1,140 @@ +/* + * JXON.js + * Ratatosk + * + * Created by Alexander Ljungberg on March 15th, 2012. + * + * Public domain JXON implementation from algorithm #3 of: + * https://developer.mozilla.org/en/Parsing_and_serializing_XML + * + * Any copyright is dedicated to the Public Domain. + * + * Modified by Andrew (Pat) Patterson, 2015 from original at + * https://github.com/wireload/Ratatosk/blob/master/jxon.js + * to preserve case of element and attribute names + */ + +JXON = function() +{ + +}; + +JXON.buildValue = function(sValue) +{ + if (/^\s*$/.test(sValue)) + return null; + if (/^(true|false)$/i.test(sValue)) + return sValue.toLowerCase() === "true"; + if (isFinite(sValue)) + return parseFloat(sValue); + // Don't do this - it'll parse anything that looks like a date and get the timezone wrong. + // https://bugzilla.mozilla.org/show_bug.cgi?id=693077 + //if (isFinite(Date.parse(sValue))) + // return new Date(sValue); + return sValue; +}; + +JXON.fromXML = function(xmlString) +{ + return JXON.getJXONData((new DOMParser()).parseFromString(xmlString, "text/xml")); +}; + +JXON.getJXONData = function(oXMLParent) +{ + var vResult = /* put here the default value for empty nodes! */ null, + nLength = 0, + sCollectedTxt = ""; + if (oXMLParent.hasAttributes && oXMLParent.hasAttributes()) + { + vResult = {}; + for (nLength; nLength < oXMLParent.attributes.length; nLength++) + { + oItAttr = oXMLParent.attributes.item(nLength); + vResult["@" + oItAttr.nodeName] = JXON.buildValue(oItAttr.value.replace(/^\s+|\s+$/g, "")); + } + } + if (oXMLParent.hasChildNodes()) + { + for (var oItChild, sItKey, sItVal, nChildId = 0; nChildId < oXMLParent.childNodes.length; nChildId++) + { + oItChild = oXMLParent.childNodes.item(nChildId); + if (oItChild.nodeType === 4) + { + sCollectedTxt += oItChild.nodeValue; + } /* nodeType is "CDATASection" (4) */ + else if (oItChild.nodeType === 3) + { + sCollectedTxt += oItChild.nodeValue.replace(/^\s+|\s+$/g, ""); + } /* nodeType is "Text" (3) */ + else if (oItChild.nodeType === 1 && !oItChild.prefix) + { /* nodeType is "Element" (1) */ + if (nLength === 0) + vResult = {}; + sItKey = oItChild.nodeName; + sItVal = JXON.getJXONData(oItChild); + if (vResult.hasOwnProperty(sItKey)) + { + if (vResult[sItKey].constructor !== Array) + vResult[sItKey] = [vResult[sItKey]]; + vResult[sItKey].push(sItVal); + } + else + { + vResult[sItKey] = sItVal; + nLength++; + } + } + } + } + if (sCollectedTxt) + nLength > 0 ? vResult.keyValue = JXON.buildValue(sCollectedTxt) : vResult = JXON.buildValue(sCollectedTxt); + /* if (nLength > 0) { Object.freeze(vResult); } */ + return vResult; +}; + +JXON.loadObj = function(oParentObj, oParentEl, oNewDoc) +{ + var nSameIdx, + vValue, + oChild; + for (var sName in oParentObj) + { + vValue = oParentObj[sName]; + if (sName === "keyValue") + { + if (vValue !== null && vValue !== true) + oParentEl.appendChild(oNewDoc.createTextNode(String(vValue))); + } + else if (sName.charAt(0) === "@") + oParentEl.setAttribute(sName.slice(1), vValue); + else + { + oChild = oNewDoc.createElement(sName); + if (vValue && vValue.constructor === Date) + oChild.appendChild(oNewDoc.createTextNode(vValue.toGMTString())); + else if (vValue && vValue.constructor === Array) + { + for (nSameIdx = 0; nSameIdx < vValue.length; nSameIdx++) + JXON.loadObj(vValue[nSameIdx], oChild); + } + else if (vValue && vValue instanceof Object) + { + JXON.loadObj(vValue, oChild, oNewDoc); + } + else if (vValue !== null && vValue !== true) + oChild.appendChild(oNewDoc.createTextNode(vValue.toString())); + + oParentEl.appendChild(oChild); + // CPLog.error("Document: " + (new XMLSerializer()).serializeToString(oNewDoc)); + } + } +}; + +JXON.toXML = function(oJXONObj, rootName) +{ + var oNewDoc = document.implementation.createDocument("", "", null), + rootNode = oNewDoc.createElement(rootName || 'xml'); + oNewDoc.appendChild(rootNode); + JXON.loadObj(oJXONObj, rootNode, oNewDoc); + return (new XMLSerializer()).serializeToString(oNewDoc); +}; diff --git a/mobile.html b/mobile.html index c1a14eb..9c07cad 100644 --- a/mobile.html +++ b/mobile.html @@ -55,13 +55,8 @@ // OAuth var client = new forcetk.Client(clientId, loginUrl, proxyUrl);; -// We use $j rather than $ for jQuery -if (window.$j === undefined) { - $j = $; -} - -$j(document).ready(function() { - $j('#login').popupWindow({ +$(document).ready(function() { + $('#login').popupWindow({ windowURL: getAuthorizeUrl(loginUrl, clientId, redirectUri), windowName: 'Connect', centerBrowser: 1, @@ -79,7 +74,6 @@ function sessionCallback(oauthResponse) { if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') { - //$j('#prompt').html('Error - unauthorized!'); errorCallback({ status: 0, statusText: 'Unauthorized', @@ -91,10 +85,10 @@ addClickListeners(); - $j.mobile.changePage('#mainpage',"slide",false,true); - $j.mobile.pageLoading(); + $.mobile.changePage('#mainpage',"slide",false,true); + $.mobile.pageLoading(); getAccounts(function(){ - $j.mobile.pageLoading(true); + $.mobile.pageLoading(true); }); } } diff --git a/mobile.page b/mobile.page index 40105bf..c3f54e8 100644 --- a/mobile.page +++ b/mobile.page @@ -50,20 +50,17 @@ an HTML5 mobile app using jQuery Mobile diff --git a/mobileapp.js b/mobileapp.js index 8d7d1b6..eeb9242 100644 --- a/mobileapp.js +++ b/mobileapp.js @@ -35,85 +35,85 @@ function errorCallback(jqXHR){ } function addClickListeners() { - $j('#newbtn').click(function(e) { + $('#newbtn').click(function(e) { // Show the 'New Account' form e.preventDefault(); - $j('#accountform')[0].reset(); - $j('#accformheader').html('New Account'); + $('#accountform')[0].reset(); + $('#accformheader').text('New Account'); setButtonText('#actionbtn', 'Create'); - $j('#actionbtn').unbind('click.btn').bind('click.btn', createHandler); - $j.mobile.changePage('#editpage', "slide", false, true); + $('#actionbtn').unbind('click.btn').bind('click.btn', createHandler); + $.mobile.changePage('#editpage', "slide", false, true); }); - $j('#deletebtn').click(function(e) { + $('#deletebtn').click(function(e) { // Delete the account e.preventDefault(); - $j.mobile.pageLoading(); - client.del('Account', $j('#accountdetail').find('#Id').val() + $.mobile.loading('show'); + client.del('Account', $('#accountdetail').find('#Id').val() , function(response) { getAccounts(function() { - $j.mobile.pageLoading(true); - $j.mobile.changePage('#mainpage', "slide", true, true); + $.mobile.loading('hide'); + $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); }); - $j('#editbtn').click(function(e) { + $('#editbtn').click(function(e) { // Get account fields and show the 'Edit Account' form e.preventDefault(); - $j.mobile.pageLoading(); - client.retrieve("Account", $j('#accountdetail').find('#Id').val() + $.mobile.loading('show'); + client.retrieve("Account", $('#accountdetail').find('#Id').val() , "Name,Id,Industry,TickerSymbol", function(response) { - $j('#accountform').find('input').each(function() { - $j(this).val(response[$j(this).attr("name")]); + $('#accountform').find('input').each(function() { + $(this).val(response[$(this).attr("name")]); }); - $j('#accformheader').html('Edit Account'); + $('#accformheader').text('Edit Account'); setButtonText('#actionbtn', 'Update'); - $j('#actionbtn') + $('#actionbtn') .unbind('click.btn') .bind('click.btn', updateHandler); - $j.mobile.pageLoading(true); - $j.mobile.changePage('#editpage', "slide", false, true); + $.mobile.loading('hide'); + $.mobile.changePage('#editpage', "slide", false, true); }, errorCallback); }); } // Populate the account list and set up click handling function getAccounts(callback) { - $j('#accountlist').empty(); + $('#accountlist').empty(); client.query("SELECT Id, Name FROM Account ORDER BY Name LIMIT 20" , function(response) { - $j.each(response.records, + $.each(response.records, function() { var id = this.Id; - $j('

  • ') + $('
  • ') .hide() .append('

    ' + this.Name + '

    ') .click(function(e) { e.preventDefault(); - $j.mobile.pageLoading(); + $.mobile.loading('show'); // We could do this more efficiently by adding Industry and // TickerSymbol to the fields in the SELECT, but we want to // show dynamic use of the retrieve function... client.retrieve("Account", id, "Name,Id,Industry,TickerSymbol" , function(response) { - $j('#Name').html(response.Name); - $j('#Industry').html(response.Industry); - $j('#TickerSymbol').html(response.TickerSymbol); - $j('#Id').val(response.Id); - $j.mobile.pageLoading(true); - $j.mobile.changePage('#detailpage', "slide", false, true); + $('#Name').text(response.Name); + $('#Industry').text(response.Industry); + $('#TickerSymbol').text(response.TickerSymbol); + $('#Id').val(response.Id); + $.mobile.loading('hide'); + $.mobile.changePage('#detailpage', "slide", false, true); }, errorCallback); }) .appendTo('#accountlist') .show(); }); - $j('#accountlist').listview('refresh'); + $('#accountlist').listview('refresh'); if (typeof callback != 'undefined' && callback != null) { callback(); @@ -124,20 +124,20 @@ function getAccounts(callback) { // Gather fields from the account form and create a record function createHandler(e) { e.preventDefault(); - var accountform = $j('#accountform'); + var accountform = $('#accountform'); var fields = {}; accountform.find('input').each(function() { - var child = $j(this); + var child = $(this); if (child.val().length > 0 && child.attr("name") != 'Id') { fields[child.attr("name")] = child.val(); } }); - $j.mobile.pageLoading(); + $.mobile.loading('show'); client.create('Account', fields, function(response) { getAccounts(function() { - $j.mobile.pageLoading(true); - $j.mobile.changePage('#mainpage', "slide", true, true); + $.mobile.loading('hide'); + $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); } @@ -145,21 +145,21 @@ function createHandler(e) { // Gather fields from the account form and update a record function updateHandler(e) { e.preventDefault(); - var accountform = $j('#accountform'); + var accountform = $('#accountform'); var fields = {}; accountform.find('input').each(function() { - var child = $j(this); + var child = $(this); if (child.val().length > 0 && child.attr("name") != 'Id') { fields[child.attr("name")] = child.val(); } }); - $j.mobile.pageLoading(); + $.mobile.loading('show'); client.update('Account', accountform.find('#Id').val(), fields , function(response) { getAccounts(function() { - $j.mobile.pageLoading(true); - $j.mobile.changePage('#mainpage', "slide", true, true); + $.mobile.loading('hide'); + $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); } @@ -167,5 +167,5 @@ function updateHandler(e) { // Ugh - this is required to change text on a jQuery Mobile button // due to the way it futzes with things at runtime function setButtonText(id, str) { - $j(id).html(str).parent().find('.ui-btn-text').text(str); + $(id).text(str).parent().find('.ui-btn-text').text(str); } diff --git a/phonegap.html b/phonegap.html deleted file mode 100644 index 1e80547..0000000 --- a/phonegap.html +++ /dev/null @@ -1,253 +0,0 @@ - - - - - - Accounts - - - - - - - - - - - - - - -
    -
    -

    Login

    -
    -
    - Connecting to Force.com -
    -
    -

    Force.com

    -
    -
    -
    -
    -

    Account List

    -
    -
    -
    - -
    -
      -
    -
    - -
    -
    -
    -

    Force.com

    -
    -
    -
    -
    -

    Account Detail

    -
    -
    - - - - -
    Account Name:
    Industry:
    Ticker Symbol:
    -
    - - - -
    -
    -
    -

    Force.com

    -
    -
    -
    -
    -

    New Account

    -
    -
    -
    - - - - - - - - - - - - - - -
    Account Name:
    Industry:
    Ticker Symbol:
    - -
    -
    -
    -

    Force.com

    -
    -
    - -