Friday, August 4, 2017

Sorting Tables In Visualforce

A List of records returned by select query can be sorted using order by clause. The field with which the resulting list be sorted should be specified after the order by clause.

We can specify whether we want a ascending sorting or a descending sorting. If the ascending or descending is not specified then the query sorts in ascending order of the specified field.

For ascending just use the keyword "'ASC" and for descending use the keyword "DESC"
example:

1. List<Contact> conList = [select id,name,email from contact order by name desc];
2. List<account> accList = [Select id,name,accountnumber from account order by name asc] is same as below
3.List<account> accList = [Select id,name,accountnumber from account order by name]
Here's an example that sorts a table showing 5 account records. Button sorts the table depending on the field selected for sorting.


Visualforce Page:

<apex:page controller="sortDemoController">
 <apex:form >
  <apex:pageBlock >
   <apex:panelgrid columns="2">
    <apex:selectList value="{!selectedField }" size="1">
     <apex:selectOption itemValue="Name" itemLabel="Account Name"/>
     <apex:selectOption itemValue="AccountNumber" itemLabel="Account Number"/>
     <apex:selectOption itemValue="Annualrevenue" itemLabel="Annual Revenue"/>
    </apex:selectList>
    <apex:commandButton value="Sort Table" action="{!sortMethod}" reRender="pgblcktbl"/>
   </apex:panelgrid>
  </apex:pageBlock>
  <apex:pageBlock >
   <apex:pageblocktable value="{!accList}" var="rec" id="pgblcktbl">
     <apex:column value="{!rec.name}"/>
     <apex:column value="{!rec.annualrevenue}"/>
     <apex:column value="{!rec.accountnumber}"/>
   </apex:pageblocktable>
  </apex:pageBlock>
 </apex:form>

</apex:page>


Controller:

Public with sharing class sortDemoController {
Public List<account> accList{get;set;}
Public string selectedField {get;set;}
 Public sortDemoController(){
  accList = [select name,accountnumber,annualrevenue from account limit 5];
 }
 Public void sortMethod(){
  if(selectedField == 'Name')
     accList = [select name,accountnumber,annualrevenue from account where id IN:accList order by Name limit 5 ];
  else if(selectedField == 'AccountNumber')
     accList = [select name,accountnumber,annualrevenue from account where id IN:accList order by AccountNumber limit 5 ];
  else if(selectedField == 'Annualrevenue')
    accList = [select name,accountnumber,annualrevenue from account where id IN:accList order by Annualrevenue desc limit 5 ];
 }

}

Thursday, August 3, 2017

Batch apex scheduling in apex - batch apex job run for every 15 minutes or 30 minutes

We can schedule a batch apex using declarative way/OOTB, for this we need to write the schedule class that calls the batch apex class. Using declarative way we can schedule the class either weekly or monthly basis.

In weekly, we can have it run every day or any selected day of week. For a particular day we can specify a preferred time at which the class run. So, using declarative way we can have a highest frequency of 1 time per day not more than that. That is it does not support to run the class more number of times per day. Say, you want the class to run every 1 hour, or every 30 mins, then you cannot do it using declarative way. To do this, we can use system.schedule method and call the scheduler class. 

System.schedule takes 3 parameters as below :

system.schedule('jobname',timeperiod,scheduler class name)

jobname: you can give any name to your job
timeperiod: specify the time frequency with which the job should run
scheduler class name: scheduler class that calls your batch apex class.

timeperiod should be specified in below format:
Seconds Minutes Hours Day_of_month Month Day_of_week optional_year

For example, to run every 30 mins the expression would be : 0 30 * * * ?

here '*' means every time against the specified parameter, every hour, every day of month, every day of week and '?' means no specific value. Thus, this expression means every 30 minutes. So, the system.schedule('testname',0 30 * * * ?,schedulerclass()); would call the schedulerclass every 30 minutes when the statement executes.

You can visit salesforce documentation to know more on system.schedule parameters.


Lets write a simple batch apex class, its scheduler class and then, execute system.schedule method to run that batch apex every 30 minutes.
Batch Apex Class:

global class BatchApexDemo implements database.batchable<sobject>{
Public string soqlquery;
 Public void setQry(string soqlquery){
    this.soqlquery = 'Select name,status from account limit 1';
 }
 global database.querylocator start(database.batchableContext bc){
  return database.getquerylocator(soqlquery);
 }
 global void execute(database.batchablecontext bd, list<sobject> sc){
   System.debug('**In Execute Method**');
 }
 Public void finish(database.batchableContext bc){
  
 }
}

Scheduler class along with method that will Can scheduler class every 30 minutes:



Scheduler class along with method that will Can scheduler class every 30 minutes:
global with sharing class ScheduleBatchApexDemo implements Schedulable {
global void execute(SchedulableContext sc) {
  ID BatchId = Database.executeBatch(new BatchApexDemo(), 200);
}

Public static void SchedulerMethod() {
  string timeinterval = '0 30 * * * ?';
  System.schedule('BatchApexDemo-Every15mins',timeinterval, new ScheduleBatchApexDemo());
  }
}


Now, we have to just execute the "SchedulerMethod" once, this will keep on calling the batch apex every 30 minutes. We can use developer console to execute this method. Just execute below statement to call the method: ScheduleBatchApexDemo.SchedulerMethod();



Tuesday, August 1, 2017

SOQL/DML should not be allowed to enter a FOR loop

This rule is Salesforce 101. No DML or SOQL statement should be inside for loop, even if you are running the loop for only two records.

    for(Contact c: ContactList){
    //THIS IS A NO NO NO
           account a = [Select id,name from Account where id=:c.accountid];
           c.name=c.name+a.name;
    //THIS IS A EVEN BIGGER NO
update c;  

}



The code written above is a recipe for disaster. Instead the same code can be optimized as:



for(Contact c: ContactList){
    accountSet.add(c.accountid);
}
//Whuuu huuu not inside any loop
Map<id,Account> accountMap = new Map<id,Account>([Select id,name from Account where id=: accountSet]);
for(Contact c: ContactList){
    //Like they say in treasure hunt movies, a map comes in handy.
    c.name=c.name+ accountMap.get(c.accountid).name;
}

update ContactList;



Use Collections Set, Map wherever possible:

         If in your code you have to loop inside a loop, make sure to use a map instead of a list for the inner loop. When we use a map, it is easier to fetch data and will save you a lot of time. Using map also helps speed up the code.


for(Contact c: ContactList){
    for(account a: accountList){
        if(c.accountid==a.id){
            //do something awesome
        }
    }

}

This code is good enough but can be optimized even more like this

for(Contact c: ContactList){
    if(c.accountid==accountMap.get(c.accountid)){
        //do something awesome
    }

}

AggregateResult In SalesForce



Requirement:  To retrieve number of employees with salary greater than 25000, we would use : 



LIST<AggregateResult> noOfEmployees = new LIST<AggregateResult> (); noOfEmployees = [SELECT COUNT(id) noOfEmp FROM Employee__c WHERE salary__c > 25000 ]; for(AggregateResult sobj : noOfEmployees)
{
 Integer empNumber = Integer.valueOf(sobj.get('noOfEmp'));

}

How To Get Current Page URL In Apex?

How To Get Current Page URL In Apex?
Ans:
        Sometime we need to get current page URL in apex ,Then we need to use Apexpages.currentPage() methods provided by salesforce.
There is following step which you need to follow:
Step 1:
First call ‘getHeaders()’ method which return a map of the request headers,where the key string contains the name of the header, and the value string contains the value of the header.
After that get the ‘Host’ key value from that map.
String hostVal  = ApexPages.currentPage().getHeaders().get(‘Host’);
It gives like ‘c.ap1.visual.force.com’,etc.
Step 2:
Second,you need to call ‘getUrl()’ method which returns the relative URL associated with the PageReference,including any query string parameters and anchors.
String urlVal = Apexpages.currentPage().getUrl();
It returns as ‘/apex/pagename’,’/apex/pageName?check=false’ etc.
Step 3: After that add these two values return in step1 and step2 with ‘https://’
The whole method is given below:
public void getPageURL() {
    String hostVal  = ApexPages.currentPage().getHeaders().get(‘Host’);
    String urlVal = Apexpages.currentPage().getUrl();
    String URLL = ‘https://’ + hostVal+ urlVal;
}

How To Check The Object Accessibility On Visualforce Page?

How To Check The Object Accessibility On Visualforce Page?
  Ans:
       If a user has insufficient privileges to view an object, any Visualforce page that uses a controller to render that object will be inaccessible. To avoid this type error, we should ensure that our  Visualforce components will only render if a user has access to the object associated with the controller.
You can check for the accessibility of an object this way:
{!$ObjectType.objectname.accessible}
In the same way you can check either the current user has the permission to create,update,delete etc. any object with the following methods :
{!$ObjectType.objectname.createable}
{!$ObjectType.objectname.updateable}
{!$ObjectType.objectname.deletable}
Refer the following URL :
http://www.salesforce.com/us/developer/docs/api/Content
/sforce_api_calls_describesobjects_describesobjectresult.htm
I’ll give you a small example :
Suppose you have added a “Delete” button to delete the account records in your VF page,but an user with custom profile did not have permission to delete the account records. So how you hide that button for a particular user in same VF page. You need to use the above method to hide that button

<apex:commandButton value="DELETE" action="{!doDelete}" rendered="{!$ObjectType.account.deletable}"/>



salesforce interview questions and answers Part-4


Which type of report can be used for dashboard components?
Ans : Summary and matric report.

How many types of dashboard components are available?
Ans : Chart, Table, Metric and Gauge.

Explain dynamic Dashboard.
Ans : Dashboard which is running under current logged in user permission are known as “dynamic Dasboard”. At the most 3 dynamic dashboards can be built. Available in Unlimited, Enterprise and developer edition. This type of dashboard cannot be scheduled for refresh. IT must be scheduled manually.

What is the default timeout period while calling webservice from Apex.
Ans : 10 sec.

A single Apex transaction can make how many callouts to an HTTP request or an API call ?
Ans : Maximum 10 callouts

How to increase timeout while calling web service from Apex ?
Ans :

     docSample.DocSamplePort stub = new docSample.DocSamplePort();
     stub.timeout_x = 2000; // timeout in milliseconds

How to show loading image while Ajax call in Visualforce? OR how to show image in <apex:actionStatus> tag in Visualforce?
Ans:

        <div style="position:absolute;top:20px;left: 50%;">
            <apex:actionStatus id="refreshContent" >
               <apex:facet name="start" >
                 <apex:image url="{!$Resource.LoadingImage}" />
               </apex:facet>
             </apex:actionStatus>
        </div>

What is features of “Manage Members” in campaign records? Ans :
Campaign members are created from lead, contact, or person account records. Salesforce provides a variety of ways in which you can manage your campaign members. You can add and update up to 50,000 campaign members at a time through lead, contact, and person account reports; you can search for and add or edit multiple leads and contacts from the Manage Members page; you can add an unlimited number of leads and contacts using a CSV import file; or you can add members to a campaign one at a time from contact or lead detail pages.
If user doesn’t have any right on particular record and have only read level access at object level. Can he change the record owner?
Ans : Yes. In profile, there is setting for “Transfer Record”.
How to hide the “App Setup” Menu from user’s setup page? Ans : In Profile, remove access “View Setup and Configuration”.
While creating new profile for user, which existing profile should be copied?
Ans: If the new user is not System administrator then copy from “Standard User” profile.
Who can run reports? Ans : Users with permission “Run Report” and access to report folder can only run the report.
What is Difference between “printable View” and “Export Details” button on report? Ans: Printable View: formatting, grouping and subtotals are persisted. Export Details: formatting, grouping and subtotals are lost.
What is the use of “floating report header”?
Ans: If you have long tabular report, you can make the column header visible on each pages as you scroll, by enabling floating report headers.
How to enable “floating report header”? 
Ans : Go to “Setup | App Setup | Customize | Report and Dashboard | User Interface Settings “. Click on checkbox “Enable Floating Report Headers”.
Which permission is required to set the running user other than you in dashboard?
Ans: “View All Data” in profile.
Who can access “drag and drop dashboard”?
Ans : User with permission “manage dashboard”.
nherit; color: #1a1a1a; font-f
amily: Merriweather, Georgia, serif; margin-bottom: 1.75em; white-space: normal;"> How to round the double to two decimal places in Apex? Ans:
Decimal d = 100/3;
Double ans = d.setScale(2) ;
In Profile settings, what is difference between “Modify All Data” and “Modify All” ?

Ans:
Modify All Data : Create, edit, and delete all organization data, regardless of sharing settings.
Modify All : Give Read, Add, Delete permission to selected Object, Create permission is not included in Modify All  permission.

f i want record level access then what should i use from Salesforce security model?

Ans: Manual Sharing

If i want Object level access then what should i use from Salesforce security model?

Ans: Profile
In case of Master-Detail relationship, on Update of master record can we update the field of child record using workflow rule?

Ans: No

In case of Master-Detail relationship, on Update of child record can we update the field of Parent record using workflow rule?

Ans: Yes, the Master fields are also available for “Criteria evaluation”.

While setting OWD (Organization wide sharing), can we change/modify the setting of child record in case of Master-Detail relationship?

Ans: No, Child record is controlled by the Parents setting.

What is the need of “Custom Controller” in Visualforce as everything can be done by the combination of Standard Controller + Extension class. Ans :
Sharing setting is applied on standard object/extension by default; In case we don’t want to apply sharing setting in our code then Custom controller is only option.
It is possible that the functionality of page does not required any Standard object or may require more than one standard object, then in that case Custom controller is required.
n class declaration if we don’t write keyword “with sharing” then it runs in system mode then why keyword “without sharing” is introduced in apex? Ans:
Lets take example, there is classA declared using “with sharing” and it calls classB method. classB is not declared with any keyword then by default “with sharing” will be applied to that class because originating call is done through classA. To avoid this we have to explicitly define classB with keyword “without sharing”.

salesforce interview questions and answers Part-3

What causes Concurrent Apex limit error in Salesforce ?

Ans : If Synchronous Apex runs more than 5 sec it considered as long running job. And we have limit that only 10 long running job can execute at a time. So, whenever 11th Synchronous apex tries to execute, it gets Concurrent Apex limit error.

What is custom metadata type ? 

Ans :
 Custom metadata was introduced generally in Summer 15 release. Before Custom metadata type, we were using Custom settings of List type. Problem with custom setting was that, during migration or in packages, data were not migrated. We had to either use data loader or some API to create initial data. However, if we package custom metadata type or migrate it, data will also be migrated along with it.


Which component in Salesforce ends with “__mdt” and “__s”?
Ans : Custom metadata types ends with “__mdt” (meta data type), just like custom object or custom fields ends with “__c”.
When we create Geolocation field in Salesforce, lets say by name “location__c” then internally Salesforce creates subfields with extension “__s“. In this case “location_latitude__s” and “location_longitude__s”.
Difference between Chatter API and Connect API.
Ans :
Chatter API is REST API for Chatter to display Salesforce data, especially in mobile applications. Responses are localized, structured for presentation, and can be filtered to contain only what the app needs
Connect API provides apex classes for accessing the same data available in Chatter REST API. Use Chatter in Apex to create custom Chatter experiences in Salesforce.
Which custom fields or relationships in salesforce ends with “__pc” and “__pr” ?
Ans : In normal scenario all custom fields ends with “__c” and relationships ends with “__r” However for Person accounts, custom fields ends with “__pc” and custom relationship ends with “__pr”.
How to report on User License field?
Ans :    Create formula field in User Object with formula “Profile.UserLicense.Name”.
Note: You need to copy and paste this value because it doesn’t show up in the fields drop down.
While creating JavaScript button to execute anonymous apex, what should you keep in mind ?
Ans : End user must needs to have “Apex Author” permission and this is something should not be granted to end user. Also, while creating JavaScript button, user must be aware that its only supported in Salesforce classic and not in Salesforce Lightning.
How to add the Document Header in Visualforce page?
Ans : Directly there is no way to add the document type in visualforce. However in most of the cases IE9 does not work with Visualforce pleasantly. And then we need to add the Document type in header. So following workaround will work.
1<apex:outputText
2escape="false"
3value="{!'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'}"/>
4<html>
5    <head>
6        <title>test</title>
7    </head>
8    <body>test</body>
9</html>
10</apex:page>

Onchange event does not work with <apex:actionsupport> in IE9. How to resolve this error?
Ans: If we hide the Header on Visualforce page then it creates lots of problem in IE9. I think there are few java-script library loaded by Header of Salesforce which makes IE9 compatible. So the best solution is to enable the Headre by using “showHeader=true” in Apex page.
If IE9 is not working with your custom visualforce page then how to tell your visualforce code to run in IE8 compatibility mode?
Ans:
Add following metatag to pages:
1<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

It may happen that above tips will not work as lots of time the page header already sent. then how to achieve same result using Apex?
Ans:
Add below line of code in Apex (Constructor)
1Apexpages.currentPage().getHeaders().put('X-UA-Compatible''IE=8');

Read more:  https://developer.salesforce.com/blogs/developer-relations/2011/03/visualforce-rerender-and-internet-explorer-9.html

You want to display the Encrypted field on Visualforce and you are using component apex:outputText. Will it work for Encrypted fields?

Ans : Encrypted custom fields that are embedded in the <apex:outputText> component display in clear text. The <apex:outputText> component doesn’t respect the View Encrypted Data permission for users. To prevent showing sensitive information to unauthorized users, use the <apex:outputField> tag instead.

Will below query work? Explain.
1SELECT COUNT(Id), Name, Address__c FROM Opportunity GROUP BY Name
Ans :
Above query will throw an error.
Explanation : In Group by clause the columns selected must be either used in Group by clause or in aggregate functions. The Name field is neither used in aggregate methods and in group by clause and hence will result in error “Malformed Query”
 Explain difference in COUNT() and COUNT(fieldname) in SOQL.
Ans :
COUNT()
COUNT() must be the only element in the SELECT list.
You can use COUNT() with a LIMIT clause.
You can’t use COUNT() with an ORDER BY clause. Use COUNT(fieldName) instead.
You can’t use COUNT() with a GROUP BY clause for API version 19.0 and later. Use COUNT(fieldName) instead.
COUNT(fieldName):
You can use COUNT(fieldName) with an ORDER BY clause.
You can use COUNT(fieldName) with a GROUP BY clause for API version 19.0 and later.

How to write the “Where” clause in SOQL when GroupBy is used for aggregate functions?
Ans : We cannot use the “Where” clause with GroupBy for aggregate functions like SUM() instead we will need to use the “Having Clause“.
Example : Get all the opportunity where more than one record exists with same name and name contains “ABC”.
1SELECT COUNT(Id) , Name FROM Opportunity GROUP BY Name  Having COUNT(Id) > 1 AND Name like '%ABC%'
Lets consider that the first component in VF page is the Datepicker. In that case whenever the page loads, salesforce auto focus the first component resulting in Datepicker onfocus event. Because of this the Datepicker component opens automatically. How we can avoid this?
Ans :
On load event, write the javascript code to autofocus any other field or any other non-visible component.
Example :
1<span id="focusDistraction"></span>
2<script type="text/javascript">
3    /* prevent autopup of the date inputfield by the default focus behavoir */
4    window.onload=function() {
5    document.getElementById('focusDistraction').focus();
6    }
7</script>