Friday, 26 April 2013

Excerpts from the Salesforce Mobile Developer Week organized on 23rd April 2013 in Bangalore


On 23rd April 2013, I attended Salesforce Mobile Developer Week | Developer Force.com event Bangalore location. The event was hosted by Sandeep Bhanot , a Salesforce evangelist at Salesforce.com.

I would like to divide this blog into two parts; one talking about an statistics (which I liked very much) shown during the event  and the other showing useful links to get to know Salesforce mobile apps development.

Part 1

One statistics that I saw during the event was that "Apple's iPhone business is now bigger than whole of Microsoft | Mail Online". My first thought was like this: I could not believe this. I have grown up hearing all about Microsoft and Bill Gates. They are there from a long time. How could a small innovation all of a sudden could surpass this big mammoth. I then did Google search and found this Forbes report.

So much of talk on the above Forbes statistics. Lets move ahead with the event updates. 

Part 2

Sandeep started talking about Salesforce Touch, the Salesforce mobile application. To sum up, Salesforce Touch is built on HTML5 technology, so it’s easy to add the Sales app to any mobile tablet or handset. That means your company can focus on growing sales, not building and maintaining infrastructure. As of now, officially Salesforce Touch is supported on iPhone and iPad.
For mobile app development, Salesforce has introduced Salesforce Platform Mobile Services tol  rapidly build enterprise mobile apps. To know more about this services, click here Mobile Application Development with Salesforce Platform Mobile Services  | Developer Force.com. The services introduced Mobile Packs( namely jQuery Mobile | jQuery MobileAngularJS — Superheroic JavaScript MVW Framework and Backbone.js ) to jumpstart web mobile development with leading open-source JavaScript frameworks.


Moreover, I get to know some ways of data binding in Salesforce. They are:

In the end, I would like to share some other important source of information which could be needed for mobile apps development.


Explore these resources and enjoy how to develop Salesforce mobile apps.

Happy mobile apps development !!! 



Tuesday, 12 February 2013

Usage of StandardSetController Class and Methods


StandardSetController Class
===================
-StandardSetController objects allow you to create list controllers similar to, or as extensions of, the pre-built Visualforce list controllers provided by Salesforce.

-This is useful for writing pages that perform mass updates (applying identical changes to fields within a collection of objects).

-Fields that are required in other Salesforce objects will keep the same requiredness when used by the prototype object.

Instantiation
========

-You can instantiate a StandardSetController in either of the following ways:

-From a list of sObjects:
List accountList = [SELECT Name FROM Account LIMIT 20];
ApexPages.StandardSetController ssc = new   ApexPages.StandardSetController(accountList);

-From a query locator:
ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Name,CloseDate FROM Opportunity]));

-Note:
-The maximum record limit for StandardSetController is 10,000 records.
-Instantiating StandardSetController using a query locator returning more than 10,000 records causes a LimitException to be thrown.
-However, instantiating StandardSetController with a list of more than 10,000 records doesn’t throw an exception, and instead truncates the records to the limit.

Methods
=======

-StandardSetController methods are all called by and operate on a particular instance of a StandardSetController.



Example
======

The following example shows how a StandardSetController object can be used in the constructor for a custom list controller:

public class opportunityList2Con {
    // ApexPages.StandardSetController must be instantiated
    // for standard list controllers
    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                    [SELECT Name, CloseDate FROM Opportunity]));
            }
            return setCon;
        }
        set;
    }

    // Initialize setCon and return a list of records
    public List getOpportunities() {
        return (List) setCon.getRecords();
    }
}


The following Visualforce markup shows how the controller above can be used in a page:

   
   
   
       
           
           
       
   



     

Friday, 8 February 2013

How to use ANT for metadata backup & deployments?



We generally take metadata backups from Salesforce as a part of our regular deployments. And what I have noticed is that using ANT is faster that that of Eclipse.

Following are the manual things that we generally do while taking the backup using ANT.
1) Change the username and password to point to that particular org in the build.properties.
2) Change the server url to point to either sandbox or prod.
3) Change the name of the backup folder once the backup is taken – add a prefix or suffix of current date.
The following steps help you to prevent the above manual changes every time you use ANT to take a backup.
1) Open the build.properties and create your own variables (for storing the credentials) for different Orgs as shown below.



2) Create a date variable to store the current date in the same build.properties as shown below


#Date variable
sf.date = 01-22-2013


3) Now open the build.xml from the same folder as that of build.properties and create the targets as shown below.
Note that each target is using the org specific variables that we created in build.xml
Note that the dir attribute (in mkdir tag) and retrieveTarget attribute (in sf:retrieve tag) are using the date variable as suffix.

 


4)You are Done!
Now every time you take a back you don’t have to change the credentials to point to that org. All you have to do is change the date variable value to the current date.
Now open ANT in command prompt and type in ant as shown below.


Some points to consider into:


While installing ANT, I found three problems.

So, I thought to make you know this earlier to installing on your system.

If you get an error like these, do the prescribed solution. It would work! 
          D:\Software\apache-ant-1.8.4-bin\apache-ant-1.8.4\bin>ANT -version
          Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre7\lib\tools.jar
          Apache Ant(TM) version 1.8.4 compiled on May 22 2012
    • Solution: Make sure you have tools.jar file in the above mentioned path.
   2.
          D:\Software\apache-ant-1.8.4-bin\apache-ant-1.8.4\bin>ANT Dev1Backup
          Buildfile: D:\Software\apache-ant-1.8.4-bin\apache-ant-1.8.4\bin\build.xml

          Dev1Backup:
              [mkdir] Created dir: D:\Software\apache-ant-1.8.4-bin\apache-ant-1.8.4\bin\Dev1Backup_01-22-2013

          BUILD FAILED
          D:\Software\apache-ant-1.8.4-bin\apache-ant-1.8.4\bin\build.xml:23: Problem: failed to create task or type antlib:com.salesforce:retrieve
          Cause: The name is undefined.
          Action: Check the spelling.
          Action: Check that any custom tasks/types have been declared.
          Action: Check that any / declarations have taken place.
          No types or tasks have been defined in this namespace yet

          This appears to be an antlib declaration.
          Action: Check that the implementing library exists in one of:
                  -D:\Software\apache-ant-1.8.4-bin\apache-ant-1.8.4\bin\..\lib
                  -C:\Documents and Settings\sudhir.kumarjaiswal\.ant\lib
                  -a directory added on the command line with the -lib argument

    • Solution: Make sure to add ant-salesforce.jar file inside lib folder (here for example put it inside D:\Software\apache-ant-1.8.4-bin\apache-ant-1.8.4\lib
    3.
          D:\Software\apache-ant-1.8.4-bin\apache-ant-1.8.4\bin>ANT Dev1Backup
          Buildfile: D:\Software\apache-ant-1.8.4-bin\apache-ant-1.8.4\bin\build.xml

          Dev1Backup:

          BUILD FAILED
          D:\Software\apache-ant-1.8.4-bin\apache-ant-1.8.4\bin\build.xml:23: Invalid username, password, security token; or user locked out. Are you at a new location?
          When accessing Salesforce--either via a desktop client or the API--from outside of your companyÆs trusted networks,
          you must add a security token to your password to log in.
          To receive a new security token, log in to salesforce.com at http://login.salesforce.com and click      Setup | My Personal Information | Reset Security Token.

    • Solution: Make sure to append Security token at the end of password in build.properties file.
      • P.S: You may need this security token when you are not connected to the VPN.

Thursday, 7 February 2013

How to Integrate Social Networking Sites like Facebook and Twitter into Salesforce?



1. Install the app “Salesforce for  Twitter and Facebook (v4.6)” from appexchange

2. Select “Salesforce for Social Media” app from the app drop down menu

3. Create a Facebook page or Twitter account in Facebook or Twitter respectively
In Salesforce, create new facebook page by using “Facebook Page” tab. Give that page an identifying name and enter the facebook page id from your facebook account.

4. Now it’s time to validate the page created inside Salesforce: Goto the given facebook user and click “Grant Facebook Access”. Select the facebook page you want to validate and assign it to that user as Admin.

5. To activate scheduled searches into these social networking sites:
Follow Social Setup ---------? Scheduled Searched ------? Select time interval

6. Click on “Conversation” to view and reply to them

7. Click on “Social Publisher” to :
Insert message: to Twitter, Facebook and/or Chatter at one go.
(Or, you can use “Social Agent” to share any comments)
Get conversation: from any Twitter a/c or Facebook pages

8. You can convert any of the particular conversation into:
Create Contact
Add to campaign (only for Twitter)
Create Lead
Create Case
Post to chatter
Create Solution
And many more…

9. To validate a user: Follow this step
Facebook Users--? Grant Facebook Access? Log in to use your Facebook account with CRM







Force.com Programming Best Practices




Apex
  • Since Apex is case insensitive you can write it however you’d like. However, to increase readability, follow Java capitalization standards and use two spaces instead of tabs for indentation.
  • Use Asychronous Apex (@future annotation) for logic that does not need to be executed synchronous.
  • Asychronous Apex should be “bulkified”.
  • Apex code must provide proper exception handling.
  • Prevent SOQL and SOSL injection attacks by using static queries, binding variables or the escapeSingleQuotes method.
  • When querying large data sets, use a SOQL “for” loop
  • Use SOSL over SOQL where possible – it’s much faster.
  • Use Apex Limits Methods to avoid hitting governor exceptions.
  • No SOQL or SOSL queries inside loops
  • No DML statements inside loops
  • No Async (@future) methods inside loops
  • Do not use hardcoded IDs

Triggers

  • There should only be one trigger for each object.
  • Avoid complex logic in triggers. To simplify testing and resuse, triggers should delegate to Apex classes which contain the actual execution logic. See Mike Leach’s excellent trigger template for more info.
  • Bulkify any “helper” classes and/or methods.
  • Trigers should be “bulkified” and be able to process up to 200 records for each call.
  • Execute DML statements using collections instead of individual records per DML statement.
  • Use Collections in SOQL “WHERE” clauses to retrieve all records back in single query
  • Use a consistent naming convention including the object name (e.g., AccountTrigger)

Visualforce

  • Do not hardcode picklists in Visualforce pages; include them in the controller instead or you can use Custom Settings for larger picklist values.
  • Javascript and CSS should be included as Static Resources allowing the browser to cache them.
  • Reference CSS at the top and JavaScript a the bottom of Visualforce pages as this provides for faster page loads.
  • Mark controller variables as “transient” if they are not needed between server calls. This will make your page load faster as it reduces the size of the View State.
  • Use to iterate over large collections.
  • Use the cache attribute with the component to take advantage CDN caching when appropriate

Unit Testing

  • Use a consistent naming convention including “Test” and the name of the class being tested (e.g., Test_AccountTrigger)
  • Test classes should use the @isTest annotation
  • Test methods should create all data needed for the method and not rely on data currently in the Org.
  • Use System.assert and System.assertEquals liberally to prove that code behaves as expected.
  • Test each branch of conditional logic
  • Write test methods that both pass and fail for certain conditions and test for boundary conditions.
  • Test triggers to process 200 records – make sure your code is “bulkified” for 200 records and doesn’t throw the dreaded “Too many SOQL queries: 21″ exception.
  • When testing for governor limits, use Test.startTest and Test.stopTest and the Limit class instead of hard-coding governor limits.
  • Use System.runAs() to execute code as a specific user to test for sharing rules (but not CRUD or FLS permissions)
  • Execute tests with the Force.com IDE and not the salesforce.com UI. We’ve seen misleading code coverage results when running from the salesforce.com UI.
  • Run the Force.com Security Source Scanner to test your Org for a number of security and code quality issues (e.g., Cross Site Scripting, Access Control Issues, Frame Spoofing)


For Reference:

How to deal with the error: "Maximum View State size limit (135KB) exceeded" ?


Whenever I have worked on some Web Services requirement, I have generally come across this error message : "Maximum View State size limit (135KB) exceeded".
This time I encountered this known error when I was working on Account Online Passwords enhancement for February Release 2013
So today I am taking time to jot down the way to minimize the probability of getting this error.

Few points about view state here:

The view state of a web page is composed of all the data that's necessary to maintain the state of the controller during server requests (like sending or receiving data). Since the view state contributes to the overall size of your page, performance of a page can depend on efficiently managing the view state.

  1. Salesforce allows Visualforce pages to have a maximum view state size of 135KB. The View State tab shows you which elements on your page are taking up that space. A smaller view state size generally means quicker load times.
  2. To minimize your pages' view state, you can optimize your Apex controller code and remove any superfluous Visualforce components used.
  3. For example:
    1. If you notice that a large percentage of your view state comes from objects used in controllers or controller extensions, consider refining your SOQL calls to return only data that's relevant to the Visualforce page.
    2. If your view state is affected by a large component tree, try reducing the number of components your page depends on.
    3. Another important point here is the use of Transient keyword. The Transient variable can not be saved, and shouldn't be transmitted as part of the view state for visual force page.

Point to be noted down is that:

  • Any apex component under tag are counted against View State size. So this could be reduced by using HTML/CSS/JavaScript components because they are not counted against apex view state limit.
  • Try using JavaScript Remoting instead of using apex action tags. In addition to decreasing view state size, you could get data near to real time.

I could show you a scenario where  how I reduced the View State size from around 136KB to around 85KB just by replacing with HTML tags 
in conjuction with tag.

Initial piece of code:

















Refined piece of code























Note: However, here we need to use CSS for formatting Table header values.

So we can see how significantly the view state size is reduced just by replacing one apex tag with HTML tag. 

Supporting Links: