Monday 30 July 2018

Apex Batch - Is execute method called if start returns 0 results?


No. Execute will not be called unless at least one non-null item is available for processing. "scope" will never be empty or null, because execute won't be called if there's nothing to do.

Saturday 21 July 2018

How to save map with List as child and Id as parent
In this following Example,I had taken case as a example
Map<Id, List<Case>> parentChildCase = new Map<Id, List<Case>>();
Map<ID, Case> childMap = new Map<ID, Case>([SELECT Id, ..., FROM Case]);

for(ID c : childMap .keySet())
{
    if(parentChildCase.containsKey(childMap .get(c).ID))
    {
        parentChildCase.get(cMap.get(c).ID).add(childMap .get(c));
    }
    else
    {
        List<Case> cases = new List<Case>();
        cases.add(childMap .get(c));
        parentChildCase.put(childMap .get(c).ID, cases);
    }
}


Thursday 19 July 2018

Apex Code Coverage Hack


Declaimer: please be aware that all things into this article are “bad practice” and should not be used constantly, it might be used for a really urgent production deployment when you have faced with a broken tests and as a result a code coverage has dropped down than 75% and you has been blocked.

As you know salesforce requires at least 75% test coverage for production deployment. You can find the following statement in documentation:

The code coverage percentage for a class or trigger displayed on the Apex Classes or the Apex Triggers page includes a fraction between parentheses with the numbers used to compute this percentage, for example, 90% (72/80). The code coverage percentage is calculated by dividing the number of lines covered by tests by the total number of lines that are part of the coverage calculation. Some lines of code are excluded from code coverage calculation, such as:


  • Comments
  • System.debug statements
  • Test methods

A code statement that is broken up into multiple lines—only the first line is counted
To generate code coverage results, you must run your Apex tests first. If no tests have been run, no code coverage data will exist and 0% (No coverage data) displays for classes (except for test classes) and triggers on the Apex Classes and Apex Triggers pages.

Cool! The code coverage calculation is pretty simple and we can cheat the system. Just use the following code


/*
Please improve your tests and remove this class as soon as possible
*/
public class CodeCoverageHack {
    public static void hack() {
        Integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        // you can continue this method with i++; up to 3000 lines
        // after that you would be stoped by limit of size
        // but you can create a few such methods
 }

    public static void hack1() {
         // do the same thing ...
    }

    @isTest static void runTest() {
        CodeCoverageHack.hack();
        CodeCoverageHack.hack1();
        //...
        CodeCoverageHack.hackN();
    }
}
That’s all.   ✌

How to run future method in test class


We have to use future method inside the  startTest/stopTest:

Test.startTest();
myClass.futuremethod( someID );
Test.stopTest();

Test.stopTest() does not return until your future method has completed.

How to find in which  release my org is running?


On the Home tab, on the top right of the screen is a link to Summer 18 for Developers. This indicates our org release.


Wednesday 18 July 2018


How to add your Company Logo  in salesforce home Tab:

Login into your salesforce account,

upload the image under documents tab
  • Go to yourname --> setup -->appsetup -->Customize-->homepage component 
  • Under the custom component click New and then click next 
  • Give the Name as Logo and select the type as image, click next
  • Click the insert image button and select the image/logo file
  • Then click save
Now we are successfully uploaded logo into salesforce, next step is we need to enable the custom component in the home page layout
  • Go to yourname --> setup -->appsetup -->Customize-->homepage layout
  • Click edit the layout
  • Then select our component after that click next
  • Move our custom component in the top of the left side column
  • Then click the save button  
That's it, We are done! Company logo is added into your salesforce account click the Home button.


Custom Label

These are custom text value that can be accessed from Apex classes or Visual force pages. These values can be translated into any language Salesforce supports. 

Custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language. 

Limitation

You can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length.

How to access custom label in visualforce page:
{!$Label.demolabel}

How to access custom label in Apex classes:

System.Label.Label__Name;

For In my example:
System.Label. demolabel

Tuesday 17 July 2018


Customize error message for trigger and display error message below the field

This Post demonstrates how to display error message in particular field level.

SObject SomeRecord;
SomeRecord.SomeField__c.addError('Custom Message');
//or
SomeRecord.someField__c.addError(someException);

Note:

We cannot add it to a field dynamically. This error mapping can only be done with a hard-coded field.


aura:method in Salesforce


  • This enables you to directly call a method in a component’s client-side controller instead of firing and handling a component event.
  • Using <aura:method> simplifies the code needed for a parent component to call a method on a child component that it contains. 
ParentComp:


<aura:component description="parentComponent" access="global" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes">
    <c:childComponent aura:id="childQuestion"/>
    <button type="button" aura:id="saveAndReturn" class="slds-button" onclick="{!c.save}">Save and return
    </button>  
</aura:component>

Controller:

({
    save : function(component,helper,event){
 var childComponent = component.find("childQuestion");
        childComponent.getScoreMethod('aa','bb','cc');
    }
})


childComponent.cmp


<aura:component description="childComponent" access="global">
    <aura:method name="getScoreMethod" action="{!c.calcScore}" access="PUBLIC">
        <aura:attribute name="contactId" type="String" />
        <aura:attribute name="contactName" type="String"  />
        <aura:attribute name="recordId" type="String"  />
    </aura:method>

</aura:component> 


({
    calcScore : function(component,event,helper){
        var args = event.getParam("arguments");
        var contactId = args.contactId;
        var contactName = args.contactName;
        var recod=args.recordId;
       alert('Inside Calc Score: ' + contactId + ' - ' + contactName+'-'+recod);
    }
})


Application:


<aura:application >
 <c:ParentComp/>
</aura:application>


Custom setting Setting type not visible




You Can enable list custom setting schema Setting Page
Setup > schema Setting Page > List custom Setting




After Enabling,
  


    




List has no rows for assignment to SObject  error

 Consider following query:
   
      id p;
      user u = [SELECT Id from user where Name = :username];
      if (u != null)
      p = u.Id;

  •  The above code will fail if there is no user record with the matching username. It doesn't actually return a null.


 It would be safer to do the following:

    id p;
     user[] userlist = [SELECT Id from user where Name = :username];
     if (userlist.size() > 0)
       p = userlist[0].Id;

Monday 16 July 2018


Trigger for Adding and removing User to Permission set based on User roles


trigger AssignPermissionSet on User (after insert,after Update) {
    PermissionSet pereset = [SELECT Id FROM PermissionSet WHERE Label ='SBU Impact Visible'];
    Set<ID> addIds = new Set<Id>(),
            removeIds = new Set<Id>(),
            roleIds = new Map<Id, UserRole>([
        SELECT  Id FROM UserRole
        WHERE   Name LIKE '%E&C%' OR Name LIKE '%Commerical Ops%' OR Name LIKE '%Energy & Chemicals%' OR Name LIKE '%All Fluor%'
    ]).keySet();
    for(User record: Trigger.new) {
        (record.IsActive && roleIds.contains(record.UserRoleId)? addIds: removeIds).add(record.Id);
    }
   
    PermissionSetAssignment[] permissionSetList = new PermissionSetAssignment[0];
    addIds.removeAll(new Map<Id, AggregateResult>([SELECT AssigneeId Id FROM PermissionSetAssignment
       WHERE AssigneeId = :addIds AND PermissionSetId = :pereset.Id GROUP BY AssigneeId]).keySet());
   
    for(Id userId: addIds) {
        permissionSetList.add(new PermissionSetAssignment(PermissionSetId = pereset.id, AssigneeId = userId));
    }
    upsert permissionSetList;
    delete [SELECT Id FROM PermissionSetAssignment WHERE AssigneeId = :removeIds AND PermissionSetId = :pereset.Id];
}

Sunday 15 July 2018


Difference between Setup Audit trail and field history tracking.

 The Setup Audit Trial is on the Organization level, Field History Tracking is on the Object level. The setup audit trail history helps you track the recent setup changes that you and other administrators have made to your organization. This can be especially useful in organizations with multiple administrators.

Saturday 14 July 2018


Test code succeeds in sandbox, and fails in production test after deployment


  •     Setup-àDevelop --> Apex Text Execution
  •     Checked Disabled Parallel Apex Testing




  •   Clicked the link "View Test History" ( Clear Test Results.)


  • SetupàDevelop --> Apex Classes-àClicked "Compile all classes"
  •  Click On "Estimate your organization's code coverage" 
  • Clicked Run All Tests 
  •  Run  Apex tests again. 


Governor Limit in Salesforce:

Salesforce runs on a multitenant environment which means resources (Storage, CPU, Memory) are shared with other companies on the Salesforce platform. This means limits must be in place to ensure that all companies using the Salesforce architecture abide by certain rules and don’t let their code or processes monopolize shared resources

Friday 6 July 2018


USER LICENSE AND PROFILES:

USER LICENSE 

You may have more than one type of user license in your organization. A user license entitles a user to different functionality within Salesforce and determines which profiles and permission sets are available to the user.


·         To view a list of the active user licenses in your company, from Setup, click Company Profile àCompany Information. This page lists the following for each type of user license:
·         Status indicates the status of the license.
·         Total Licenses indicates the number of licenses for which your company is billed and that are available to you.
·         Used Licenses is the number of licenses that you have assigned to users.
·         Remaining Licenses is the number of unused licenses.



PROFILE 

Represents a user profile. A profile defines a user's permission to perform different functions within Salesforce.
Every profile Must be associated with a License. This defines what the profile can do

you can retrieve and deploy access settings for the following managed components in profiles and permission sets:
·         Apex classes
·         Custom apps
·         Custom field permissions
·         Custom object permissions
·         Custom tab settings
·         External data sources
·         Record types
·         Visualforce pages

                            PermissionSetAssignment:



  • Use the PermissionSetAssignment object to query permission set assignments to find out which permission sets are assigned to which users.
  • Each user may be assigned to many permission sets and each permission set may be assigned to many users.
  • Each PermissionSetAssignment ID represents the association of a single user and single permission set.

For example, to search for all of the permission sets assigned to a particular user:

SELECT Id, PermissionSetId
FROM PermissionSetAssignment
WHERE AssigneeId = '005600000017cKt'

To search for all users assigned to a particular permission set:

SELECT Id, AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSetId = '0PS30000000000e'

Note:

You can also create a new permission set assignment, or use delete to remove a permission set that's assigned to a user. To update an assignment, delete an existing assignment and insert a new one.

Possible Errors:



Solution:

When assigning a permission set, if the PermissionSet ​ has a UserLicenseId, its UserLicenseId and the Profile ​UserLicenseId must match.


If Permission set is already present for user.Following Error will occur.




Wednesday 4 July 2018

                                              Make a Custom Field required

Field level requirements
                                           
This is the most restrictive of requirements, and it requires the field to be entered all the time, regardless of how the record is saved (i.e. through an integration, the API, mass upload, or through the User Interface). 

On the page layout

This option only makes the field required when the specific page layout that you set this requirement on is accessed. Therefore, you could technically make this required for some users that use a particular page layout but not others. 

NOTE:  This requirement only applies when the record is edited on the User Interface.
Validation rule requirement

The simplest validation rule to make a custom field required looks like this:

ISBLANK(CUSTOM FIELD API NAME)

Or, if the field is a Number or Currency type field use this syntax:

ISNULL(CUSTOM FIELD API NAME)