Saturday, 2 February 2019

Why to use Database.Stateful()?

Database Stateful is interface. It is used in batch classes to maintain the state of the class across transactions i.e. if you want to use modified class variable in execute or finish method across multiple transactions, you have to use Database.Stateful. Only instance variable can retrieve the values between transactions. Static variables resets on each transaction.

Database.Stateful affects batch performance and therefore you should use it only if it is absolutely necessary because the class will be serialized at the end of each execute method to update its internal state. This extra serialization results in longer execution time. If possible you can use alternative method to maintain state of the variable and i.e. storing value in the object and retrieving it on each transaction. 

Friday, 1 February 2019

Salesforce Org-Wide Defaults and Object security and Ownership


** Below matrix is built considering there is no custom sharing rules or Role Hierarchy.


Object access @Profile Org-Wide Default Setting
Private Read Read/Write
Owner Other users Owner Other users Owner Other users
No Access  No Access No Access No Access No Access No Access No Access
Read Read No Access Read Read Read Read
Read/Write Read/Write No Access Read/Write Read Read/Write Read/Write


How to find field access in Permission Sets and Profile?


FieldPermission is the Salesforce internal standard object. It is used to store field permissions given through Permission set and profiles. 
For example if you want to find access of custom fields like Rate__c and Compititor__c from Account object. You can use below query to find the field usage:
SELECT SobjectType,Field, PermissionsRead,PermissionsEdit, Parent.Name, ParentId FROM FieldPermissions WHERE PermissionsRead = True and Field in ('Account.Rate__c','Account.From1__c','Account.Compititor__c') AND SobjectType = 'Account'
For Read access you can use 'PermissionsRead' and for Edit access, you can use PermissionsEdit field of FieldPermissions object. 

ParentId contains either permission set id. If you looking for field access in permission set then you can use Parent Id as it is But if you are looking for profile id then please follow:

  • When you assign FLS through profile, Salesforce stores ParentId in the form of Permission set. 
  • So to get actual profile ids, you have to add Parent.Name field in the query. 
  • That will give you 'X00e600...' id. Remove X00 from the id and rest of it is profile id. 

Path to Platform Dev II

For almost last three years I was scheduling and canceling this certification exam. There was no major reason behind it. It was just my fear to fail. In this due course of time, the exam pattern got changed (I will come to it later). Finally, in 2018, I made mind and I did not only schedule it but cleared the certification
In all these years, one thing I did not give up and that was reading salesforce related material. Be it articles, books, blogs, I read whatever came in front of me. I did not stop there. I used to take notes and paste a copy of that article beside that notes for future reference. For better understanding, I tried to implement that knowledge in real world. It really helped me not only to understand what I was reading but cleared most of my doubts that I was facing in my work. So, do not forget to read in spare time.
Now, let’s talk about the exam pattern. It contains two major sections as follows:
  • Proctored multiple-choice exam (60 multiple choice question with 120 minutes.)
  • 4 Trailhead superbadges.
You can go for either one first. I first cleared multiple choice exam and then I completed all my superbadges.

Multiple Choice Exam

For multiple choice exam, I went through each and every topic mentioned in the Salesforce exam guide. I also referred the articles from Salesforce training material. When you read these articles, Salesforce gives you more suggestions related to that topic. So, I would recommend you follow those suggestions. It worked for me and I am sure it would do for you too.
Some of the key points I would like to mention while preparing for the exam:
  • Apex Performance
  • Continuations
  • SOSL query
  • Future methods use cases
  • Callouts and limitations
  • Batch Job
  • Programmatic Sharing
  • Webservice
  • Heroku Connect
  • ActionFunction
  • Actionpollar
  • Transactions
  • External Objects
  • QueryMore
You must know Apex, Visualforce functionality thoroughly. For that, you need to have few years of hands on experience in Salesforce. REMEMBER… These are just key points that I could recollect at this point.

Superbadges

The 4 badges are as follows:
  • Apex Specialist
  • Data Integration Specialist
  • Lightning Component Framework Specialist
  • Advanced Apex Specialist.
I would recommend completing these badges with 100% honesty. You will learn a lot from them.
Takeaways:
Keep learning. Keep yourself updated with salesforce’s new features. Take all your time, go easy and keep learning.

Friday, 11 August 2017

WebServiceMock to test your Webservice Call

Salesforce is very flexible to integrate with other systems. In many projects we have lot of integrations of Salesforce with other systems. But main struggle starts while writing a test class for those integration webservices. 

Salesforce provides WebServiceMock interface to test Web service callouts of class auto-generated from a WSDL.

WebServiceMock methods:
  1. doInvoke(stub, soapRequest, responseMap, endpoint, soapAction, requestName, responseNamespace, responseName, responseType)

    • stub (Object) - An instance of the auto-generated class.
    • SoapRequest (object) - The SOAP Web service request being invoked.
    • responseMap (Map<String, Object>) - A collection of key/value pairs representing the response to send for the request.When implementing this interface, set the responseMap argument to a key/value pair representing the response desired.
    • endpoint (string) - The endpoint URL for the request.
    • soapPoint (String) - The requested SOAP operation. 
    • requestName (String) -  The requested SOAP operation name.
    • responseNameSpace (String) - Name of the response mentioned in WSDL.
    • responseType(String) - The class of the response mentioned in auto-generated class.

The methods in the auto-generated WSDL class call WebServiceCallout.invoke, which performs the callout to the external service. 
When testing these methods, you can instruct the Apex runtime to generate a fake response whenever WebServiceCallout.invoke is called. 
To do so, implement the WebServiceMock interface and specify a fake response for the Apex runtime to send. Here are the steps in more detail.

@isTest
global class WebServiceMockImpl implements WebServiceMock {
   global void doInvoke(
           Object stub,
           Object request,
           Map<String, Object> response,
           String endpoint,
           String soapAction,
           String requestName,
           String responseNS,
           String responseName,
           String responseType) {
        


           webserviceClass.RequestRecipientTokenResponse reqTokem= new webserviceClass.RequestRecipientTokenResponse();
            reqTokem.RequestRecipientTokenResult = 'test';
            response.put('response_x', reqTokem);

}

Now in your actual test class just before calling your actual webservice invoke method, just instruct Apex runtime to send fake response by calling:

Test.setMock(WebServiceMock.class, new WebServiceMockImpl());         //At this line it is asking WebServiceMockImpl to generate fake response for invoke method defined in webserviceClass


You can use same WebServiceMockImpl class for multiple different calls. For that you have to use parameters of doInvoke() method to check what type of web service call has made.

For example:
Our WSDL class is:
       Gobal class docSample{

                                Public class DocSamplePort{
                                    public docSample.EnvelopeStatus CreateAndSendEnvelope(docSample.Envelope Envelope) {
                                                WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              'http://www.docSample.net/API/3.0/SendEnvelope',
              'http://www.docSample.net/API/3.0',
              'SendEnvelope',
              'http://www. docSample.net/API/3.0',
              'SendEnvelopeResponse',
              docSample.SendEnvelopeResponse_element'}
                                                );
                                                }
                               


                                public String RequestSenderToken(String EnvelopeID,String AccountID,String ReturnURL) {
                                                WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              'http://www.docSample.net/API/3.0/ RequestSenderToken,
              'http://www.docSample.net/API/3.0',
              'SendEnvelope',
              'http://www. docSample.net/API/3.0',
              'SendEnvelopeResponse',
              docSample. RequestSenderTokenResponse_element }
                                                );

                                }



   }

And our main class(let’s say docuSampleLanding.cls) calling these below webservices are:
1.     docSample. DocSamplePort es = dsApiSend.CreateAndSendEnvelope(DSEnvelope);

2.     token = dsApiSend.RequestRecipientToken(envelopeId, recipient_captiveinfo_ClientUserId, recipient_UserName, recipient_Email, assert, clientURLs);


While writing test class for docuSampleLanding.cls whenever your Apex runtime hits webservice call, it will give your error.
To avoid that just write below line of code:
Test.setMock(WebServiceMock.class, new WebServiceMockImpl()); 
And in WebServiceMockImpl class use multiple if statements t odetermine which web service call has been made.
For example:
global class WebServiceMockImpl implements WebServiceMock {
   global void doInvoke( Object stub, Object request, Map<String, Object> response, String endpoint, String soapAction, String requestName, String responseNS, String responseName, String responseType) {

        if(requestName =='RequestRecipientToken'){
            docSample.RequestRecipientTokenResponse_element reqTokem= new docSample.RequestRecipientTokenResponse_element();
            reqTokem.RequestRecipientTokenResult = 'test';
            response.put('response_x', reqTokem);
        }
        if(requestName =='CreateAndSendEnvelope'){
             docSample.CreateAndSendEnvelopeResponse_element respElement = new docSample.CreateAndSendEnvelopeResponse_element();
      
               docSample.EnvelopeStatus es=new docSample.EnvelopeStatus();
               es.EnvelopeID='test';      
               respElement.CreateAndSendEnvelopeResult = es;
               response.put('response_x', respElement);

        }

}

Wednesday, 29 July 2015

External Organization-Wide Defaults Overview

External Organization-Wide Defaults Overview


External organization-wide defaults provide separate organization-wide defaults for internal and external users. They simplify your sharing rules configuration and improve recalculation performance. Additionally, administrators can easily see which information is being shared to portals and other external users.
The following objects support external organization-wide defaults.
  • Accounts and their associated contracts and assets
  • Cases
  • Contacts
  • Opportunities
  • Custom Objects
  • Users
External users include:
  • Authenticated website users
  • Chatter external users
  • Community users
  • Customer Portal users
  • Guest users
  • High-volume portal users
  • Partner Portal users
  • Service Cloud Portal users


****Chatter external users have access to the User object only.

Previously, if your organization wanted Public Read Only or Public Read/Write access for internal users but Private for external users, you would have to set the default access to Private and create a sharing rule to share records with all internal users.
With separate organization-wide defaults, you can achieve similar behavior by setting the default internal access to Public Read Onlyor Public Read/Write and the default external access to Private. These settings also speed up performance for reports, list views, searches, and API queries.

Friday, 24 July 2015

Creating, Assigning and Checking Custom Permissions


Creating, Assigning and Checking Custom Permissions

I have been wanting to explore Custom Permissions for a little while now, since they are now GA in Winter’15 i thought its about time i got stuck in. Profiles, Permission Sets have until recently, been focusing on granting permissions to entities only known to the platform, such as objectsfieldsApex classes and Visualforce pages. In most cases these platform entities map to a specific feature in your application you want to provide permission to access.
However there are cases where this is not always that simple. For example consider a Visualforce page you that controls a given process in your application, it has three buttons on it RunClear History and Reset. You can control access to the page itself, but how do you control access to the three buttons? What you need is to be able to teach Permission Sets and Profiles about your application functionality, enter Custom Permissions!
CustomPermissions
CustomPermission
NOTE: That you can also define dependencies between your Custom Permissions, for example Clear History and Reset permissions might be dependent on a Manage Important Process  custom permission in your package.
Once these have been created, you can reference them in your packaged Permission Sets and since they are packaged themselves, they can also be referenced by admins managing your application in a subscriber org.
SetCustomPermissions
The next step is to make your code react to these custom permissions being assigned or not.

New Global Variable $Permission

You can use the $Permission from a Visualforce page or as SFDCWizard points out here from Validation Rules! Here is the Visualforce page example given by Salesforce in their documentation.
1
2
3
<apex:pageBlock rendered="{!$Permission.canSeeExecutiveData}">
   <!-- Executive Data Here -->
</apex:pageBlock>

Referencing Custom Permissions from Apex

In the case of object and field level permissions, the Apex Describe API can be used to determine if an object or field is available and for what purpose, read or edit for example. This is not going help us here, as custom permissions are not related to any specific object or field. The solution is to leverage the Permission Set Object API to query theSetupEntityAccess and CustomPermission records for Permission Sets or Profiles that are assigned to the current user.
The following SOQL snippets are from the CustomPermissionsReader class i created to help with reading Custom Permissions in Apex (more on this later). As you can see you need to run two SOQL statements to get what you need. The first to get the Id’s the second to query if the user actually has been assigned a Permission Set with them in.
1
2
3
4
5
6
7
8
9
10
11
12
List<CustomPermission> customPermissions =
    [SELECT Id, DeveloperName
       FROM CustomPermission
       WHERE NamespacePrefix = :namespacePrefix];
 
List<SetupEntityAccess> setupEntities =
    [SELECT SetupEntityId
       FROM SetupEntityAccess
       WHERE SetupEntityId in :customPermissionNamesById.keySet() AND
             ParentId IN (SELECT PermissionSetId
                FROM PermissionSetAssignment
                WHERE AssigneeId = :UserInfo.getUserId())];
Now personally i don’t find this approach that appealing for general use, firstly the Permission Set object relationships are quite hard to get your head around and secondly we get charged by the platform to determine security through the SOQL governor. As a good member of the Salesforce community I of course turned my dislike into an Idea “Native Apex support for Custom Permissions” and posted it here to recommend Salesforce include a native class for reading these, similar to Custom Labels for example.

Introducing CustomPermissionReader

In the meantime I have set about creating an Apex class to help make querying and using Custom Permissions easier. Such a class might one day be replaced if my Idea becomes a reality or maybe its internal implementation just gets improved. One things for sure, i’d much rather use it for now than seed implicit SOQL’s throughout a code base!
Its pretty straight forward to use, construct it in one of two ways, depending if you want all non-namespaced Custom Permissions or if your developing a AppExchange package, give it any one of your packaged Custom Objects and it will ensure that it only ever reads the Custom Permissions associated with your package.
You can download the code and test for CustomPermissionsReader here.
1
2
3
4
5
6
7
8
// Default constructor scope is all Custom Permissions in the default namespace
CustomPermissionsReader cpr = new CustomPermissionsReader();
Boolean hasPermissionForReset = cpr.hasPermission('Reset');
 
// Alternative constructor scope is Custom Permissions that share the
//   same namespace as the custom object
CustomPermissionsReader cpr = new CustomPermissionsReader(MyPackagedObject.SObjectType);
Boolean hasPermissionForReset = cpr.hasPermission('Reset');
Like any use of SOQL we must think in a bulkified way, indeed its likely that for average to complex peaces of functionality you may want to check at least two or more custom permissions once you get started with them. As such its not really good practice to make single queries in each case.
For this reason the CustomPermissionsReader was written to load all applicable Custom Permissions and act as kind of cache. In the next example you’ll see how i’ve leveraged the Application class concept from the Apex Enterprise Patterns conventions to make it a singleton for the duration of the Apex execution context.
Here is an example of an Apex test that creates a PermissionSet, adds the Custom Permission and assigns it to the running user to confirm the Custom Permission was granted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@IsTest
private static void testCustomPermissionAssigned() {
 
    // Create PermissionSet with Custom Permission and assign to test user
    PermissionSet ps = new PermissionSet();
    ps.Name = 'Test';
    ps.Label = 'Test';
    insert ps;
    SetupEntityAccess sea = new SetupEntityAccess();
    sea.ParentId = ps.Id;
    sea.SetupEntityId = [select Id from CustomPermission where DeveloperName = 'Reset'][0].Id;
    insert sea;
    PermissionSetAssignment psa = new PermissionSetAssignment();
    psa.AssigneeId = UserInfo.getUserId();
    psa.PermissionSetId = ps.Id;
    insert psa;
 
    // Create reader
    CustomPermissionsReader cpr = new CustomPermissionsReader();
 
    // Assert the CustomPermissionsReader confirms custom permission assigned
    System.assertEquals(true, cpr.hasPermission('Reset'));
}

Seperation of Concerns and Custom Permissions

Those of you familiar with using Apex Enterprise Patterns might be wondering where checking Custom Permission fits in terms of separation of concerns and the layers the patterns promote.
The answer is at the very least in or below the Service Layer, enforcing any kind of security is the responsibility of the Service layer and callers of it are within their rights to assume it is checked. Especially if you have chosen to expose your Service layer as your application API.
This doesn’t mean however you cannot improve your user experience by using it from within Apex Controllers,  Visualforce pages or @RemoteAction methods to control the visibility of related UI components, no point in teasing the end user!

Integrating CustomerPermissionsReader into your Application class

The following code uses the Application class concept i introduced last year and at Dreamforce 2014, which is a single place to access your application scope concepts, such as factories for selectors, domain and service class implementations (it also has a big role to play when mocking).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Application {
 
    /**
     * Expoeses typed representation of the Applications Custom Permissions
     **/
    public static final PermissionsFactory Permissions = new PermissionsFactory();
 
    /**
     * Class provides a typed representation of an Applications Custom Permissions
     **/
    public class PermissionsFactory extends CustomPermissionsReader
    {
        public Boolean Reset { get { return hasPermission('Reset'); } }
    }
}
This approach ensures their is only one instance of the CustomPermissionsReader per Apex Execution context and also through the properties it exposes gives a compiler checked way of referencing the Custom Permissions, making it easier for application developers code to access them.
1
2
3
4
if(Application.Permissions.Reset)
{
  // Do something to do with Reset...
}
Finally, as a future possibility, this approach gives a nice injection point for mocking the status of Custom Permissions in your Apex Unit tests, rather than having to go through the trouble of setting up a Permission Set and assigning it in your test code every time as shown above.

This information is extracted from http://andyinthecloud.com/ 

Why to use Database.Stateful()?

Database Stateful is interface. It is used in batch classes to maintain the state of the class across transactions i.e. if you want to use ...