How to create visualforce page using Streaming API

Streaming API allows to push data (whenever records are created or updated in the backend) to a visualforce page opened by a user without refreshing page. It is very much similar to push notifications in mobile apps. You can refer Streaming API developer guide to get additional details regarding streaming API. Since it is an API in Salesforce, you can connect to it using multiple ways. You can build a java client application to connect to Salesforce. In this post, we will cover how to create a visualforce page using streaming API. This page will show newly created opportunities without reloading the page.

Steps to Use

1) Create a push notification in Salesforce

    Streaming API works on the model of subscribing to push notifications. So first step is to create a push notification at the salesforce end to which we can subscribe from the visualforce page we are going to create. In this post we will create a push notification on opportunity object. Easiest way to create this is execute below code in developer console,

2) Create visualforce page and controller to subscribe to this push notification

    Cometd JavaScript library is used to get data in JSON format to visualforce page. Then using this JavaScript data can be rendered to visualforce page. In the example given below, controller queries 10 opportunity records and displays as a table in page level. Thereafter whenever new opportunities are created in the backend, streaming API pushes data as JSON to page and using JavaScript this data is appended at the end of the table.


 

In the page a static resource is used with JavaScript libraries like cometd, JSON2 etc. You can find the static resource in Salesforce Sample Codes Github project.

Please note that streaming API usage is counted against a 24hour daily limit. Exact limit varies with edition of salesforce. For developer edition it is 10000 in 24 hours.

How to build autocomplete fields in visualforce pages

It is a very handy option to have autocomplete in picklists/dropdowns with large number of options. In this blog we will cover how to use a multiselect autocomplete field in a visualforce page. image

In this example we will display a list of email addresses configured in a custom setting as autocomplete options in an input field. It will also demonstrate how to pass the value that user is selecting to the controller.

It works based on jQuery UI autocomplete feature. Necessary css and JavaScript is available in CDN. you can find links to these CDN files in the visualforce page code.

Steps to Use

1) Create a custom setting and create records

   In this example, the list of email addresses that are displayed in autocomplete is pulled from name field in a custom setting. Please create a list custom setting with name AutocompleteEmails(AutocompleteEmails__c). Then create some email addresses as entry in the custom setting.

2) Create a page and controller

   Code used for achieving it can be found below,

 

   In the constructor of the class, email addresses are queried from the custom setting. Then these values are converted to JSON. This JSON file is assigned to a property in the controller, which is accessible in the page. Then in page level, using this JSON, autocomplete feature is created. Since <apex:inputText does not support applying autocomplete feature on it, autocomplete is created in a regular input field. The values that user select in this regular input is passed to controller using an <apex:inputHidden field. In the save method, this value is passed to controller and it is printed using a System.debug() statement.

Usage

This feature will be very useful when users are using a dropdown with large number of options in a visualforce page. This will help users to find the value they are searching for very easily.

How to send email using apex

From Salesforce you can send emails using multiple methods. Commonly we will be image using workflows to send emails. But it is common to come across requirements that require more sophisticated email which might contain attachments. Please check below to see sample code to send email with attachments using apex,

Steps to Use

1) Get details regarding email body, attachments, to address etc.

    You need get some basic details and take some design considerations before starting development. Salesforce allows only 10 emails to be sent in one apex transaction. So if you are sending email from a trigger for each record it will fail, when data is loaded through data loader in bulk. In addition to this, there will be organization level limit in number of emails that can be sent in one day. But this limit is usually high(1000 x number of users).

3) Reuse below code to send simple email (minimum example)

    Please check below code sample to send a very simple email from apex.


3) Reuse below code to send email with attachment (full example)

    Please check below code sample to send email from apex.


This sample code receives a string of TO email addresses separated by commas, a String of CC email addresses separated by commas, email subject and email body as string. This method also creates a text attachment in the email.

4) Additional reference

    In addition to the methods used above there are many built in salesforce methods and supporting class related to sending emails. Please check below links for additional details,

Single Outbound email

Messaging Class

Send Email Result

How to use Google Charts in Visualforce pages

Usually you might come across requirements to show charts in visualforce page.image Salesforce’s built in analytics solutions is good. You can even embed those charts in your regular visualforce pages without much difficulty. But the only limitations is that some types of charts are not available in visualforce page. Another one common use case is community pages. Salesforce charts can be used in community, only if users have partner community or community user plus licenses, which are bit more costly. In such cases, you will have to go for third party charting solutions like Google Charts, Fusion charts etc. Here is an example of how to embed a Google chart in visualforce page.

Steps to Use

1) Understand the data requirements of the chart you need

    You can find the list of all Google charts at charts gallery. Once you have found the right chart for your requirement, you need to check the data requirements of the chart. Each chart requires data in some specific format.

2) Format data in visualforce page controller in the required format

    Once you have found the right format for data, next step is to format data in that format before sending to chart.

3) Visualforce page and controller implementation of doughnut chart

    Check out below code where a doughnut chart is displayed with attendance of student. In the controller different attendance values are aggregated and passed that to page level using properties,





Use Cases

  • Whenever charts need to be shown in visualforce pages
  • Wherever standard Salesforce charts are not fitting your requirements
  • If you have regular community licenses and want to show charts to users, Google charts is a good alternative.

 

Integration between Java app and Salesforce – Partner WSDL

It is very common for any Salesforce developer to come across scenarios involving integrationsalesforcecodes logo between Salesforce and other systems. Most of these systems are based on JAVA. In this post we will cover how to integrate between Salesforce and a locally running Java application. The same logic and code can be used to connect to Salesforce from a web based java application also.

Steps to integrate

1) Download Partner WSDL from your sandbox 

    You can find Partner WSDL in your salesforce sandbox under Setup – Develop – API. Download partner WSDL file from above location to your local system folder.

2) Get WSC (Webservice connector) jar file provided by salesforce.  

    This jar file was initially provided by salesforce as .jar itself. Force.com webservice connector is a high performance webservice client stack implemented using a streaming parser. This gives some advantages compared to regular java classes generated from partner WSDL using other WSDL to Java tools. You can find source code to latest version of source code in force.com WSC github.

First clone the repository to your system and then build jar file using the instructions given.

3) Generate Partner.jar using WSC (Webservice connector) jar generated in step 2  

    You can convert partner WSDL into a jar file using WSC jar file. It is single command from command line, which can be found in the above github link.

4) Create project in eclipse 

    By the end of step 3 you have all the components needed for connecting to salesforce. Now create a new java project in eclipse. Import wsc.jar from step 2 and partner.jar from step 3 as external libraries. Then create a new class with name “PartnerExample” in the project. Then copy paste the code below,

It should compile without any error. Use Runas Java application option in eclipse to run the project. This code queries 5 contact and creates an account

Reference links

There is lot of good resources demonstrating similar connectivity options between salesforce and java applications. Please check below links,

How to pass ADM 201–Salesforce certified administrator

ADM 201    ADM 201 or Salesforce certified administrator certification assesses you for the knowledge required to maintain a salesforce instance in a company. It checks candidates ability to configure an application in force.com application. But it does not evaluate against coding aspects like apex and visualforce.Difficulty wise it is a bit more tougher than DEV 401. ADM 201 syllabus contains all the topics needed for DEV 401 along with some additional contents like basic knowledge in sales cloud, service cloud, chatter, reporting, user setup, securing application etc. Detailed syllabus can be found in below link.

Syllabus / Study guide 

    First and mandatory thing to do while preparing is to go through the above study guide. It will give you a very good understanding regarding different areas against which you will be assessed.

Structure of Exam

    It is a multiple choice exam with 60 questions. You will get 90 minutes to complete the exam and need 65 percentage(39 correct answers) to pass the exam. Exam fee is $200. If you failed in first attempt, second attempt can be done with a fee of $100. Most of the companies have partnership with salesforce.com through which they will be able to get vouchers for exam. So if you are from a partner company of Salesforce, try to get a voucher from your company.  

Materials to prepare

    This certification is demanded by companies looking for administrators. The role of an administrator in small to medium sized companies includes tasks like maintaining the production sandbox, creating users, managing security, running reports etc. Many business analysts who does not have plan to go to development side of salesforce.com also takes this certification. Salesforce.com recommends its “Administration Essentials for new Admins” instructor led training program as a preparation for this certification. But it is a paid training. If you cannot afford paid training, you can pass it preparing with resources available online. Also there are many people who pasted notes from salesforce training online. For example check  ADM Notes in this blog. Please find the list of other free resources to prepare for the exam,

  • Force.com Fundamentals - You can find HTML/PDF version of the book in salesforce documentation. It walks you through creating a recruiting application in force.com platform. It might look bit time consuming initially, but it is a very good resource and gives clear understanding of most of the aspects of force.com platform. Try to build recruiting application on your own with the instructions given in the book.
  • Create your own Developer Org and practice – Salesforce offers free developer org for anyone who is interested to practice. You can create your own org in registration link.
  • Online Free Training – Salesforce offers free online training videos. Once you have registered for developer org, you can access these materials from the “Help” link in top right corner of your developer org. It will give you access to lot of videos regarding different aspects of force.com platform. Again if your company is a partner of salesforce, you can get access to premium online training videos. Out of those videos “Administration Essentials for New Admins”, “Administration Essentials for Service Cloud” etc are very useful. Salesforce offers trail head training which is free and gives practical experience.
  • Online blogs – There are many good blogs explaining about all the topics in the study guide. For example you can check – Cloudsocius blog. You can check salesforce documentation for additional materials regarding any topic related to force.com platform. Just search in Google for additional new blogs. There are many coming up every day.
  • Flash card training – These are basically sample questions very similar to the actual questions in exam. This you can use as the last step in practice. Once you have gone through all materials, you will be able to answer most of the questions. If there are some questions you are not able to answer, prepare more in that area and attempt again. Some good flash card training sites are – cram , Quizlet etc.

 

I am certified. Now what?

    Congrats. It is time to celebrate. But remember that now you have to maintain your certification. Salesforce require you to maintain DEV 401 and ADM 201 certifications. Every year there will be three releases(updates to the platform) for Salesforce. Associated with each of these there will be maintenance exams. So every year you have to write thee maintenance exams. But these are online exams, based on release updates. These are easy exams, which you can clear easily if you go through release notes. After your initial certification, two consecutive release exams are free for you. But after that you will have to pay $100 every year once for maintenance exams. So always remember to take maintenance exams on time, otherwise your certifications will become invalid.

Also ADM 201 certification is a mandatory requirement before you can take Sales cloud consultant, Service cloud consultant and advanced administrator certifications. Make a good study plan and start preparing towards it.

How to pass DEV 401 - Salesforce Developer Certification

DEV 401     DEV 401 or Salesforce.com certified developer is the easiest of the salesforce certifications. It asses the capability of the candidate to configure force.com applications. But it does not cover any coding topics like apex or visualforce pages. Detailed syllabus can be found in below link.

 
    First and mandatory thing to do while preparing is to go through the above study guide. It will give you a very good understanding regarding different areas against which you will be assessed.
 

Structure of Exam

    It is a multiple choice exam with 60 questions. You will get 90 minutes to complete the exam and need 68 percentage(41 correct answers) to pass the exam. Exam fee is $200. If you failed in first attempt, second attempt can be done with a fee of $100. Most of the companies have partnership with salesforce.com through which they will be able to get vouchers for exam. So if you are from a partner company of Salesforce, try to get a voucher from your company.  

Materials to prepare

    It is a very popular certification and so very good resources are available to prepare for this certification. Salesforce.com recommends its instructor led training program, but as it is costly and it is not a difficult certification, you can very well prepare on your own and clear this certification. Below are the list of free resources to prepare for the exam,

  • Force.com Fundamentals - You can find HTML/PDF version of the book in salesforce documentation. It walks you through creating a recruiting application in force.com platform. It might look bit time consuming initially, but it is a very good resource and gives clear understanding of most of the aspects of force.com platform. Try to build recruiting application on your own with the instructions given in the book.
  • Create your own Developer Org and practice – Salesforce offers free developer org for anyone who is interested to practice. You can create your own org in registration link.
  • Online Free Training – Salesforce offers free online training videos. Once you have registered for developer org, you can access these materials from the “Help” link in top right corner of your developer org. It will give you access to lot of videos regarding different aspects of force.com platform. Again if your company is a partner of salesforce, you can get access to premium online training videos. Out of those videos “Building Applications with Force.com – Part 1" and its part 2 are very useful for DEV 401. There are many other free online video trainings like – Udacity course
  • Online blogs – There are many good blogs explaining about all the topics in the study guide. For example you can check – Cloudsocius blog. You can check salesforce documentation for additional materials regarding any topic related to force.com platform. Just search in Google for additional new blogs. There are many coming up every day.
  • Flash card training – These are basically sample questions very similar to the actual questions in exam. This you can use as the last step in practice. Once you have gone through all materials, you will be able to answer most of the questions. If there are some questions you are not able to answer, prepare more in that area and attempt again. Some good flash card training sites are – quizlet , proprofs etc.

 

I am certified. Now what?

    Congrats. Now you have to maintain your certification. Salesforce require you to maintain DEV 401 and ADM 201 certifications. Every year there will be three releases(updates to the platform) for Salesforce. Associated with each of these there will be maintenance exams. So every year you have to write thee maintenance exams. But these are online exams, based on release updates. These are easy exams, which you can clear easily if you go through release notes. After your initial certification, two consecutive release exams are free for you. But after that you will have to pay $100 every year once for maintenance exams. So always remember to take maintenance exams on time, otherwise your certifications will become invalid.

Visualforce coding best practices

Visualforce is a markup language for building user interface in Salesforce. It has some build in tags starting with “<apex:”. But these tags are finally rendered as HTML tags in UI. So if you have a good understanding in HTML, CSS and JavaScript, you can easily manipulate visualforce to give look and feel of anything possible in pure HTML. All HTML coding best practices are valid for visualforce pages also. In addition to that, please find below some best practices that are usually followed while coding visualforce pages.
  • Try to keep the view state of the page at minimum. Viewstate is basically an encrypted hidden field in the page, which contains the state of controller instance in salesforce server. It is useful for maintaining state between stateless http calls. Viewstate is created when there a form tag is present in the page. It can slow down page, if not taken care properly. Declare variables that are not needed between server calls(where state does not need to be maintained) as transients. It will not be counted against your view state limit of 135kb.
  • Never  hard code drop down values in page. Use it from controller. Also if the values are corresponding to a picklist field in the backend try retrieving, it from metadata so that in future also if some new values are added to it, it will reflect in page automatically. 
  • Render css in the page head and JavaScript at the end of the page to improve page load time.
  • Follow generic HTML web designing best practices like minifying css and JavaScript, optimizing images for web etc. Use sprites (Single big image consolidating multiple single images for css to decrease number of requests)
  • Use Cache, CDN capabilities to improve performance. If your page is not delivering dynamic content, you can increase cache value so that more data is retrieved from cache.
  • Never iterate over large collections. If collection size will exceed 1000, implement pagination. Trying to display more than 1000 will cause visualforce error. If at any time there is need to iterate over large data volume use pagination.
  • Try to decrease queries in constructor and getter methods to improve page load time. Use Ajax to load additional data.
  • If any apex controller variable/property is used in JavaScript in visualforce, encode it using {!JSENCODE(variable)}, to avoid breaking of JavaScript. Otherwise if single quotes are there in the property string, it will cause JavaScript to fail.
  • Try to use AJAX rerendering wherever applicable, instead of posting the full page content to sever. I will give faster response.
  • If page load is taking too long, try to execute some logic asynchronously using AJAX.
  • When using wrapper classes or inner classes for getting UI enhancements, post all content only if needed. For partial effects in the page if entire list of wrapper classes are passed to the controller methods, it will affect performance. Consider using action functions in such cases.
  • Implement complex and highly interactive pages using JavaScript remoting/ visualforce remoting. It will take more time in development but page will be fast as there is not viewstate. Also you can make it more flexible. 

Salesforce Apex Best Practices

Apex is the programming language used in Force.com platform.  It is an object oriented language with syntax similar to Java and working like database procedures. It is a powerful language which in conjunction with Force.com platform can help to build powerful applications with development time lesser than any other platform available today. Starting code development in apex language is very easy. But we should be very careful while developing in this platform as wrong coding practices will lead to hitting governor limits in Salesforce. Below I am listing some best practices for developing in force.com platform.
  • Apex is case insensitive. Try to follow naming conventions similar to Java. Camelcase can be used for variable names. It is better not to use underscores in variable names, even though it is allowed. If used, it can create confusion with field names in objects which contains underscores. Give one tab indentation as Java.
  • Never use queries (SOQL or SOSL) or DML Statements(Insert, Update, Delete, Upsert) inside loops.  Apex code is running in a multi-tenant environment. So Salesforce has implemented governor limits to avoid one user consuming all resources. Below screenshot shows common governor limits in Salesforce.
apex-limits
You can make only 100 SOQL queries and 20 SOSL queries in one transaction. One transaction includes all the actions that are carried out in one event. If you are calling any methods in helper classes and making some queries in that method, that also will be counted against governor limit. Also you are allowed to do DML operation on only 10000 records in a transaction. If you want to do more, you can go for asynchronous execution methods like Batch classes or @Future methods. But be careful not to call asynchronous methods also inside loops.
  • Bulkify all apex codes if possible. For the code to be efficient and avoid hitting governor limits in force.com platform, you have to bulkify all the codes.  For example check below code. Requirement is to update status of all child records when parent status is completed.


    This code may work fine initially in development if users are creating records from Salesforce UI. But if there are more than 150 child records under one completed parent record. Then this code will hit maximum number of DML queries limit. If we optimize this code we can write it as below.

    Note that query at Line number 4 will executed only once and it will pull all parent and child records.  Also there is only one DML statement at the end. If you cannot manage to achieve this through child query or relationship query, you can achieve this by using collections like Map. But you should be careful in this case, not to hit heap limit.
  • Try to externalize maximum parameters. Never hard code any Ids.  Ids changes between sandboxes (different in dev and production for same record type)Usually developers hard codes some values in code like record type id. It is not advisable. If at any place it is unavoidable, use it through custom labels or custom setting. It will be helpful if later you want to change the value.
  • Never use batch call or @future call or Email invocation in loops. It will result in hitting respective limits. Batches queues up usually. If more than 5 times same batch is queued up, it next queuing attempt will throw exception. Number of @future calls and email invocations that can be done in single transaction is 10. If it is in a loop, chances of exceeding this limit is very high.
  • Aim 100% test class coverage. It is mandatory to have a test class coverage of 75%. But more coverage means, all functionality are working as expected. Also add proper assert statements to assert test results are coming as expected.
  • Do bulk testing for triggers. If you have a trigger in any object, test it for bulk volume of records(at least above 200). This will ensure that your trigger will not fail hitting common limits. Also it ensures that your trigger is bulkified. Use organization independent test data using (seeAllData=false). It will ensure code portability between sandboxes.
  • Use indexed fields in WHERE clause of your queries in triggers. If there is an object that can contain more than 100k records. This is mandatory. Otherwise your trigger will fail, when the total volume of records crosses 100k. This is applicable only for triggers. You can find the details in Working with large SOQL queries.
  • Write test classes covering multiple profile scenarios. Use System.runAs() to run as different users. If any test method looks like reaching limit split it into many testmethods in on class, each covering different scenarios.
  • If in any test class, user data is inserted. append time stamp also to the user name. Usually if it is not append in second deployment onwards, duplicate user name error is thrown and test classes fails.
  • Use Test.StartTest() and Test.StopTest() properly to avoid hitting governor limits. If you are not trying to test triggers, keep all data insertion outside Test.StartTest() and Test.StopTest(). Test.StartTest resets governor limits. But make sure that the code that covers the class, is inside Test.StartTest().
  • Go for apex coding only if unavoidable. If it can be handled in out of the box functionality like workflow rule, approval process etc, try to do in that itself.