Wednesday, 29 January 2014

Salesforce.com Reports Explained

 There are 3 kinds of reports in salesforce.com
1) Tabular Reports
2) Summary Reports
3) Matrix Reports
Each Report has a specific use and I am listing down the scenario's in which each type of Reports will be used:-
Tabular Reports: - These kinds of reports are used when the requirement is just to view the data.
Some of the examples are:-
  • Show me all Open Opportunities
  • Show me List of all Accounts which do not have any closed opportunity
  • Show me top 10 Opportunities by revenue
Dashboards cannot be created on Tabular Reports: - Salesforce.com ADM 201 certification question
Summary Reports: - These reports are used when the requirement is to summarize only X Axis. In short if you need to do the sum or calculate the average on even one parameter then summary report is the answer.
Some of the examples are:-
  • Show sum of all Open Opportunities
  • Show opportunities subtotal by my Team
Matrix Reports: - These reports are used when the requirement is to summarize both the Axis i.e. when requirement is to group both Rows as well as Columns.
Some of the examples are:-
  • Show Accounts grouped as Customer or Prospect depending on the opportunity stage
  • Show monthly performance of Salesteam on closing opportunity by Geography for current year
Note:- Charts cannot be made on Tabular Reports as no grouping of data is available

Changing the colors for each cell in the pageblocktable

Here,

I have an object Employeetest__c with fields Name(Text),Status__c(check box) and Salary__c(Number)

Now  i want to change the color of each cell under the Salary column based on condition(for eg:if "salary<5000 then red color otherwise blue etc..) and placing the String literal for each cell under the Status column. (when checkbox is  checked it should be "Active" otherwise "InActive").

For i am writing a controller below:


public class employeetestController{

    public List<Employeetest__c> lstemp=new List<Employeetest__c>();
 
 
    public List<Employeetest__c> getrecs(){
 
        lstemp=[select name,salary__c,status__c from Employeetest__c];
        return lstemp;
 
    }
}

I am writing visualforce page using the above controller as shown below:


<apex:page controller="employeetestController"  sidebar="false">
<apex:form >
<apex:pageBlock >
<apex:pageblocktable value="{!recs}" var="e">
<apex:column value="{!e.name}"/>

<apex:column >
<apex:facet name="header">Salary</apex:facet>
<div style="background-color:{!If(e.Salary__c>=7000 &&    e.Salary__c<10000,'#7CFC00',If(e.Salary__c>=10000 && e.Salary__c<100000,'#DEB887','#DC143C'))}">
{!e.Salary__c}
</div>
</apex:column>
<apex:column >
<apex:facet name="header">Status</apex:facet>
<div>
     {!IF(e.Status__c==true,'Active','InActive')}
</div>
</apex:column>
</apex:pageblocktable>
</apex:pageBlock>
</apex:form>
 </apex:page>

Callouts in Batch Apex,State in Batch Apex

Using Callouts in Batch Apex
To use a callout in batch Apex, you must specify Database.AllowsCallouts in the class definition. For example:
global class SearchAndReplace implements Database.Batchable<sObject>, 
   Database.AllowsCallouts{
              //Business logic you want by implementing Batchable interface methods
}
Callouts include HTTP requests as well as methods defined with the webService keyword.
Using State in Batch Apex
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter is considered five transactions of 200 records each.
If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t and are reset between transactions. Maintaining state is useful for counting or summarizing records as they're processed. For example, suppose your job processed opportunity records. You could define a method in execute to aggregate totals of the opportunity amounts as they were processed.
If you don't specify Database.Stateful, all static and instance member variables are set back to their original values.
The following example summarizes a custom field total__c as the records are processed:
global class SummarizeAccountTotal implements 
    Database.Batchable<sObject>, Database.Stateful{
   global final String Query;
   global integer Summary;
  
   global SummarizeAccountTotal(String q){Query=q;
     Summary = 0;
   }
   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   }
   
   global void execute(
                Database.BatchableContext BC, 
                List<sObject> scope){
      for(sObject s : scope){
         Summary = Integer.valueOf(s.get('total__c'))+Summary;
      }
   }
global void finish(Database.BatchableContext BC){
   }
}

Print VF page on button click

VF page Code
============

<apex:page controller="bhadraPieChartController" title="Pie Chart" showHeader="false">
<script>
   //this is only the code for printing the page
    function fun(){
           document.getElementById('prnBtn').style.display='none'; 
           //document.getElementById('winBtn').style.display='none';    
           window.print();
            document.getElementById('prnBtn').style.display='block'; 
    }
</script>
<apex:form >
  <div  style="padding-left: 484px;padding-top: 27px;"><input type="button"   onClick="fun();" id="prnBtn"  value="Print This Page" style="background: green;"/></div>
</apex:form>
    <apex:chart height="350" width="450" data="{!pieData}">
        <apex:pieSeries dataField="data" labelField="name"/>
        <apex:legend position="right"/>
    </apex:chart>
</apex:page>
==========
Controller
============

public class bhadraPieChartController {


  public List<BhadraPieWedgeData> getPieData() {

       List<BhadraPieWedgeData> namedata = new List<BhadraPieWedgeData>();
 

    namedata.add(new BhadraPieWedgeData('Jan', 30));
     
    namedata.add(new BhadraPieWedgeData('Feb', 15));
     
    namedata.add(new BhadraPieWedgeData('Mar', 10));
     
    namedata.add(new BhadraPieWedgeData('Apr', 20));
     
    namedata.add(new BhadraPieWedgeData('May', 20));
     
    namedata.add(new BhadraPieWedgeData('Jun', 5));
     
    return namedata;
 
  }
 
 
 
 
    public class BhadraPieWedgeData {

     
        public String name { get; set; }
     
        public Integer data { get; set; }
     
        public BhadraPieWedgeData(String name1, Integer data1) {
               this.name = name1;          
               this.data = data1;
        }

 
    }

}
=============
Output:
==========

Print page

Tuesday, 28 January 2014

Order of execution in salesforce

When a record is saved in org with an insert, update or upsert statement following process are executed in order:


  1. The original record is loaded from the database (or initialized for an insert statement)
  2. The new record field values are loaded from the request and overwrite the old values
  3. All before triggers execute
  4. System validation occurs, such as verifying that all required fields have a non-null value, and running any user-defined validation rules
  5. The record is saved to the database, but not yet committed
  6. All after triggers execute
  7. Assignment rules execute
  8. Auto-response rules execute
  9. Workflow rules execute
  10. If there are workflow field updates, the record is updated again
  11. If the record was updated with workflow field updates, before and after triggers fire one more time (and only one more time)
  12. Escalation rules execute
  13. All DML operations are committed to the database
  14. Post-commit logic executes, such as sending email

What is difference between SOAP and REST services

SOAP (Simple Object Access Protocol):
SOAP is a method of transferring messages, or small amounts of information, over the Internet. SOAP messages are formatted in XML and are typically sent using HTTP (hypertext transfer protocol).

REST (Representational state transfer):
REST is a simple way of sending and receiving data between client and server and it don't have any much standards defined, we can send and receive data as JSON, XML or even a Text. Its Light weighted compared to SOAP.

SOAP VS REST
SOAP:

  • SOAP builds an XML protocol on top of HTTP or sometimes TCP/IP.
  • SOAP describes functions, and types of data.
  • SOAP is a successor of XML-RPC and is very similar, but describes a standard way to communicate.
  • Binary data that is sent must be encoded first into a format such as base64 encoded.

REST:
  • REST is very lightweight.
  • Typically uses normal HTTP methods instead of a big XML format describing everything. For example to obtain a resource we use HTTP GET, to put a resource on the server we use HTTP PUT. To delete a resource on the server we use HTTP DELETE.
  • REST typically is best used with Resource Oriented Architecture (ROA).
  • Binary data or binary resources can simply be delivered upon their request.

Why we use REST?
Following are few reasons to use REST:

Since REST uses standard HTTP it is much simpler in just about ever way. Creating clients, developing APIs, the documentation is much easier to understand and there aren’t very many things that REST doesn’t do easier/better than SOAP.

REST permits many different data formats where as SOAP only permits XML. While this may seem like it adds complexity to REST because we need to handle multiple formats. JSON usually is a better fit for data and parses much faster. REST allows better support for browser clients due to it’s support for JSON.

REST has better performance and scalability. REST reads can be cached, SOAP based reads cannot be cached.


Why we use SOAP?
Following are few reasons to use SOAP:

WS-Security
While SOAP supports SSL (just like REST) it also supports WS-Security which adds some enterprise security features. Supports identity through intermediaries, not just point to point (SSL). It also provides a standard implementation of data integrity and data privacy.

WS-AtomicTransaction
Need ACID Transactions over a service, you’re going to need SOAP. While REST supports transactions, it isn’t as comprehensive and isn’t ACID compliant. Fortunately ACID transactions almost never make sense over the internet. REST is limited by HTTP itself which can’t provide two-phase commit across distributed transactional resources, but SOAP can.

WS-ReliableMessaging
Rest doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying. SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.

Difference between Unmanaged Package and Managed Package in Salesforce.com




  • Unmanaged package editable by developer and Installer cannot be upgraded. In managed package certain components are locked and changes are not allowed.
  • Unmanaged package used for 1:1 distributions and managed package used for 1: Many distributions.
  • All editions can create unmanaged package and only developer edition can create managed package.

Overview of Packages in Salesforce

A package is a container for something as small as an individual component or as large as a set of related apps. After creating a package, you can distribute it to other Salesforce users and organizations, including those outside your company.

Packages come in two forms—unmanaged and managed:
Unmanaged packages
Unmanaged packages are typically used to distribute open-source projects or application templates to provide developers with the basic building blocks for an application. Once the components are installed from an unmanaged package, the components can be edited in the organization they are installed in. The developer who created and uploaded the unmanaged package has no control over the installed components, and can't change or upgrade them. Unmanaged packages should not be used to migrate components from a sandbox to production organization. Instead, use Change Sets.
Managed packages
Managed packages are typically used by salesforce.com partners to distribute and sell applications to customers. These packages must be created from a Developer Edition organization. Using the AppExchange and the License Management Application (LMA), developers can sell and manage user-based licenses to the app. Managed packages are also fully upgradeable. To ensure seamless upgrades, certain destructive changes, like removing objects or fields, can not be performed.
Managed packages also offer the following benefits:
  • Intellectual property protection for Apex
  • Built-in versioning support for API accessible components
  • The ability to branch and patch a previous version
  • The ability to seamlessly push patch updates to subscribers
  • Unique naming of all components to ensure conflict-free installs
The following definitions illustrate these concepts:
Unmanaged and Managed Packages Managed and Unmanaged Packages
Components
A component is one constituent part of a package. It defines an item, such as a custom object or a custom field. You can combine components in a package to produce powerful features or applications. In an unmanaged package, components are not upgradeable. In a managed package, some components can be upgraded while others can’t.
Attributes
An attribute is a field on a component, such as the name of an email template or the Allow Reports checkbox on a custom object. On a non-upgradeable component in either an unmanaged or managed package, attributes are editable by both the developer (the one who created the package) and the subscriber (the one who installed the package). On an upgradeable component in a managed package, some attributes can be edited by the developer, some can be edited by the subscriber, and some are locked, meaning they can’t be edited by either the developer or subscriber.
Packages consist of one or more Salesforce components, which, in turn, consist of one or more attributes. Components and their attributes behave differently in managed and unmanaged packages.
If you plan to distribute an app, it is important to consider packaging throughout the development process. For example:
  • While creating your app, consider how components and their attributes behave in different packages and Salesforce editions.
  • While preparing your app for distribution, consider how you want to release it to your customers.
  • While installing a package, consider your organization's security and license agreements.
 For information on which components can be included in a package and which attributes are editable for each component, see the Force.com Quick Reference for Developing Packages.

Monday, 27 January 2014

The Custom Setting Every Administrator Needs

As an administrator, you may want to protect data integrity by setting up validation rules that prevent users from creating, editing, and/or deleting data. Often in this situation there are certain users that are exceptions to the rule and you may find yourself writing ‘$user’ or ‘$profile’ exceptions into your validations rules to allow those users to modify records even though most users cannot.  Maintenance of the validation rules can be cumbersome over time, but using a custom setting to provide for validation rule exceptions can make this process much easier by allowing you to edit the exceptions in one place and apply it to all rules where the setting is referenced.
Business Use Case:ABC Corporation has an integration between their ERP system and Salesforce.com.  Due to this integration, they want to remove the ability to edit account names within the Salesforce.com system.  However, the system administrator and users with the contract manager profile should be allowed to edit the account names within Salesforce.com to provide for contract verbiage requests.
Custom Setting Solution:
  • From the Setup page, navigate to Build>Develop>Custom Settings
pic1





  • Click the New button;  Choose a label/name for your rule, Setting Type=Hierarchy,Visibility=Public, and enter a description
pic2
  • Create on the New button to add a custom field to your new Validation Rule Exception custom setting object
  • Choose the Checkbox field type and label/name your field ‘Run Validation Rules’ and give it adefault value of Checked

pic3
Now that we have created our custom setting object and our default behavior for running validation rules, we’ll add our profile exceptions.
  • From our new custom setting object, click on Manage
pic4
  • Set the organization default behavior by clicking the New button above the Default Organization Level Value;  The values will default appropriately in this instance to show that the default behavior will be to run validation rules, so you can just save.
  • Begin adding your exception profiles by clicking New

pic6

For this example, I will add the System Administrator with Run Validation Rule=Unchecked and the Contract Manager with Run Validation Rule=Unchecked:
pic7 pic8
The next step is to create a validation rule that prevents changes to the account name, unless the profile is part of our custom setting.  When you begin writing your validation rule, you will choose to include the new custom setting which will be visible when you click Insert Field:
pic9
  • Enter the additional criteria that should trigger the validation rule error (in this case we want the error message to appear when the account name is changed and our custom setting field  is true
pic10
  • Set up your error message and error message location and save
You can test out your new rule by attempting to edit an account name as a system administrator and then logging in as someone with any profile other than system administrator or contract manager and repeating this process to make sure you receive the error message.
In using the custom setting to determine which profiles kick off validation rules and which do not, you can maintain your validation rules and workflows from one location.  When management decides that contract managers no longer have the permission to edit account names, you can remove their profile from your custom setting rather than editing your validation rules.
Custom settings can be used in many ways (formula fields, workflow rules, as well as setting up long picklists that can be edited more easily).

How to display Custom Setting data using Apex in Visualforce page?

Sample Code:

Visualforce Page:

<apex:page controller="sample" sidebar="false" >
<apex:form >
    <apex:pageblock >
        <apex:pageblockTable value="{!code}" var="c">
            <apex:column value="{!c.Name}"/>        
            <apex:column value="{!c.Code__c}"/>
        </apex:pageblockTable>
    </apex:pageblock>
</apex:form>
</apex:page>


Apex Controller:

public class sample
{
    public List<CountryCodes__c> code {get;set;}
   
    public sample()
    {
        Map<String,CountryCodes__c> allCodes = CountryCodes__c.getAll();
        code = allCodes.values();
    }  
   
}


Output:


Difference between Custom Settings and Custom Objects



1)
Custom Settings is nothing but Cache i.e. If you want to use the records in that table no need to write any queries. If there a common static data across the Org then you can use Custom Settings.
Ex:
Map<String_dataset_name, CustomSettingName__c> mcs = CustomSettingName__c.getAll();
CustomSettingName__c mc = CustomSettingName__c.getValues(data_set_name);
If you want to access the data from Custom object then you have to write the queries.

2)
Custom object is  a record table and Custom setting is a configurations table. Custom object is like any Database table that we used to have in SQL or in any other database.
CustomSetting is like configuration file that we used to have. Even though List type of custom setting looks like that it is also a custom object but there are differences. LIke in custom settings there is a limit on no of records, you can not write trigger, workflow etc on custom setting.

3)
A custom setting is very similar to a custom object, the main difference is that the custom setting is cached.
It is especially useful to store information that will be often accessed from Apex code as it will perform better than a custom object as it doesn't have to be queried, it is also easier to manage it.