Monday, 28 July 2014

visualforce: Advanced Javascript Remoting

 
We have discussed the basic remote javascripting, here I will go with advance visualforce remote javascripting. Adavnced remote javascripting provides you flexibilty and high perfomance of pages.
  
Adding JavaScript Remoting to a Visualforce Page
To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form:
[namespace.]controller.method(
    [parameters...,]
    callbackFunction,
    [configuration]
);

namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if the class comes from an installed package.      There are two alternatives to define remote javascript without manually adding namespace. Below two examples generate namespace by its own.

 1.  Use  remoteaction global variable.
            {!$RemoteAction.classname.methodname}(
                                [parameters...,]
                                callbackFunction,
                                [configuration]
                );  

2. Use visualforce remoting manager  
        Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.AccountRemoter.getAccount}',
            accountName,
            handleResult
        );

 controller is the name of your Apex controller.

 method is the name of the Apex method you’re calling.
   
 parameters is the comma-separated list of parameters that your method takes.callbackFunction is the name of the JavaScript function that will handle the response from the controller. You can also declare an anonymous function inline. callbackFunction receives the status of the method call and the result as parameters.

configuration configures the handling of the remote call and response. Use this to change the behavior of a remoting call, such as whether or not to escape the Apex method’s response.
The remote method call executes synchronously, but it doesn’t wait for the response to return. When the response returns, the callback function handles it asynchronously.  
Here I will explain about  the configuration option  in detail. The default configuration parameters look like this: 

{ buffer: true, escape: true, timeout: 30000 } 

buffer
 Of type Boolean, whether to group requests executed close to each other in time into a single request. The default is true.
JavaScript remoting optimizes requests that are executed close to each other in time and groups the calls into a single request. This buffering improve the efficiency of the overall request-and-response cycle, but sometimes it’s useful to ensure all requests execute independently.
escape
Of type  Boolean, whether to escape the Apex method’s response. The default is true.
timeout  
 Of type integer, the timeout for the request, in milliseconds. The default is 30000 (30 seconds). The maximum is 120000 (120 seconds, or 2 minutes).

The response to a remote method call is handled asynchronously by the callback function provided in the remote method call. Your callback function will receive as parameters an event object representing the status of the remote call, and theresult object returned by the remote Apex method. Your function can update information and user interface elements on the page based on the data returned.
The event object provides values that let you act upon the success or failure of the remote call:
event.status is true on success, false on error.
event.type is the type of the response: rpc for a successful call, exception if the remote method threw an exception, and so on.
event.message contains any error message that is returned.
event.where contains the Apex stack trace, if one was generated by the remote method.
Apex primitive data types returned by result—such as strings or numbers—are converted to their JavaScript equivalents. Apex objects that are returned are converted to JavaScript objects, while collections are converted to a JavaScript array. Keep in mind that JavaScript is case-sensitive, so idId, and ID are considered different fields.
As part of a JavaScript remote call, if the Apex method response contains references to the same object, the object won't be duplicated in the returned JavaScript object, and instead, the rendered JavaScript object will contain references to the same object. An example is an Apex method which returns a list that contains the same object twice.
By default, the response of the remote call must return within 30 seconds, after which the call will time out. If your request needs longer to complete, configure a longer timeout, up to 120 seconds.
The response of the remote call has a maximum size of 15 MB.
If your JavaScript remoting code is exceeding this limit, you have several options:
Reduce the size of the response for each request. Only return data that’s required.
Break up large data retrieval into requests that return smaller chunks.
Ensure that you’re using non-batched requests. Set { buffer: false } in your remoting request configuration block.
Make batched requests less frequently, reducing the size of the batch.

Javascript Remoting and Action Fuction

<apex:actionFunction> component also lets you call controller action methods through JavaScript. Here are some differences between the two:
The <apex:actionFunction> tag:
lets you specify rerender targets
submits the form
does not require you to write any JavaScript
JavaScript remoting:
lets you pass parameters
provides a callback
requires you to write some JavaScript
In general, <apex:actionFunction> is easier to use and requires less code, while JavaScript remoting offers more flexibility.




Wednesday, 23 July 2014

How to create a Remote Call?

Visualforce remote javascripting  is a powerfull feature of force.com. It has an advantage over the actionfunction or similar ajax components which is perfomance. It is superfast and light weight, higly customisable. Here I will explain how to create remote method and call using a javascript.


Create a static controller method with @remoteaction annotation.

         public static string testRemoteCall(String input){

The method can be either public or gobal not private. Always the method has to be static. Return type can be any apex Type. @Remoteaction will make the method avaliable to a VF page through javascript object. which I will discuss later.

Here is the complete controller code.

public class testRemote{   
 
 public testRemote(){
 }

@remoteAction
public static string testRemoteCall(String input){
  return 'Hello'
}
 
public class wrapper{
  public string name;
  public integer id;
}
}

In the visualforce page the class should be added is either controller or extensions. Now you can call the controller method using a javascript.  For the above controller method  testRemoteCall there is one parameter so the remote call will have total  two parameter the latest being a callback function. Below is the javascript to call the testRemoteCall method.

 testRemote.testRemoteCall(textBoxValue ,function(result,event){ 
 //do some stuff
});
   
the second argument  is a function which is callback to hold the result of the call.  the result object will hold the return value from the controller method. Event is an object which holds the status and other parameters.
Inside the callback function you can update DOM elements.

Below is the complete code for controller and Vf.

public class testRemote{
 
 public testRemote(){
 }

@remoteAction
public static string testRemoteCall(String input){
  return  'Hello';
}
 
public class wrapper{
  public string name;
  public integer id;
}
}


<apex:page controller="testRemote">
 <input type="textbox" id="textbox"/>
 <button type="button" onclick="callRemote()" >Click</button>
 <div id="output"></div>
 <script>
function callRemote(){
 var textBoxValue = document.getElementById('textbox').value;
 testRemote.testRemoteCall(textBoxValue ,function(result,event){ 
console.log(event);
document.getElementById('output').innerHTML =  result;
 },{escape:false});
}
 </script>
</apex:page> 

Tuesday, 22 July 2014

Salesforce Rest API Vs SOAP API

 
A)SOAP API and REST API are two commonly used API's to expose your data from force.com platform to the other platforms(JAVA , .NET ,etc) or to allow external application to invoke Apex methods.

What is SOAP ?
The Simple Object Access Protocol (SOAP) is an attempt to define a standard for creating web service APIs. It is a pattern, a web service architecture, which specifies the basic rules to be considered while designing web service platforms. It typically uses HTTP as a layer 7 protocol, although this is not mandatory. The SOAP message itself consists of an envelope, inside of which are the SOAP headers and body, the actual information we want to send. It is based on the standard XML format, designed especially to transport and store structured data. SOAP may also refer to the format of the XML that the envelope uses.
SOAP is a mature standard and is heavily used in many systems, but it does not use many of the functionality build in HTTP. While some consider it slow, it provides a heavy set of functionality which is a necessity in many cases. It might now be the best solution for browser-based clients, due to its custom format.
 What is REST ?
The Representational State Transfer (REST) is another architectural pattern (resource-oriented), an alternative to SOAP. Unlike SOAP, RESTful applications use the HTTP build-in headers (with a variety of media-types) to carry meta information and use the GET, POST, PUT and DELETE verbs to perform CRUD operations. REST is resource-oriented and uses clean URLs (or RESTful URLs).

For example :
becomes

This kind of URLs syntax greatly improves both visibility and usability. It doesn’t use any query strings, and it also provides certain SEO benefits (the crawlers just love plain text). The body of the REST message can be XML, JSON or any other format, although JSON is usually the preferred choice. On the other hand, you can’t use JSON with SOAP. Or at least not entirely, because SOAP uses XML by definition for it’s envelope. It should also mentioned that REST is, by design, protocol-agnostic, although it is usually used with HTTP. 

SOAP API

1)Supports data in the form of XML only
2)Requires WSDL for the integration
3)Use SOAP API in any language that supports Web services.

REST API

1)Supports both XML and JSON format
2)Preferred for mobile and web apps since JSON being Lighter the app runs smoother and faster


Monday, 21 July 2014

Building Salesforce1 Mobile Apps with Visualforce, AngularJS, and Bootstrap



Modern web applications shift the user interface (UI) logic from the server-side to the client-side to reduce interaction latency and avoid unnecessary server requests.  This is done by running the UI logic in JavaScript. Numerous JavaScript libraries exist to help developers organize their logic and create a maintainable separation of concerns.  There also now exists numerous CSS libraries that make it easy to build a good looking UI.
One of the most popular modern JavaScript UI libraries is AngularJS since it supports data binding and makes it easy to separate the Model, View, and Controller (MVC) aspects of the UI.  For styling the UI,Bootstrap is the most popular CSS library.
Both AngularJS and Bootstrap are easy to use in Visualforce pages that work both on desktop browsers and in the Salesforce1 mobile app.


Here is a quick video walkthrough that shows how to get started:


Here is the visualforce code.
<apex:page docType="html-5.0">
<apex:stylesheet value="//cdn.jsdelivr.net/webjars/bootstrap-sf1/0.1.0-beta.6/css/bootstrap-namespaced.css"/>

<apex:includeScript value="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.11/angular.min.js"/>

   <script>
       angular.module("ngApp", []);
   </script>

   <div ng-app="ngApp">
       <form>
           <label>Name:</label>
           <input type="text" ng-model="yourName" placeholder="Enter a name here"/>
           <hr/>
           <h1>Hello {{yourName}}!</h1>
       </form>
   </div>

</apex:page>


Make sure you enable the Available for Salesforce mobile apps option when creating the Visualforce page so that it can be made available in the Salesforce1 app.  After creating the page you can create a new tab in Salesforce by going to Setup > Create > Tabsand selecting New in the Visualforce Tabs section.  To enable the new tab to show up in the Salesforce1 app go to Setup > Mobile Administration > Mobile Navigation and then add the new tab to the selected list and save it.
This is a very simple example so everything is just in one page.  As an application grows the different pieces of the JavaScript application can be separated out into different files using Static Resources.  The AngularJS and Bootstrap libraries could also be uploaded as Static Resource if you’d rather not use the public CDNs.
The Bootstrap CSS in this example uses the Salesforce1 themed version of Bootstrap so that the UI matches the look of the Salesforce1 app.
With your first AngularJS and Bootstrap enabled Visualforce page now working you are ready to build modern web apps on Salesforce1!  Also, be sure to check out the Salesforce Mobile Pack for AngularJS, which lets you quickly build mobile apps that access Salesforce data. Let us know how it goes.