Friday 21 June 2024

Create a Community User in the Test Class

Create a Community User in the Test Class 


The process for creating portal test users is more complex than creating standard test users. It may involve additional fields, and security settings.


Step 1: Create Portal Owner User


private static User createPortalAccountOwner() {
//Create a Role Role is mandatory to create a portal user
UserRole portalRole = new UserRole(DeveloperName = 'MyCustomRole', Name = 'My Role', PortalType='None' );
insert portalRole;
System.debug('portalRole is ' + portalRole);
Profile sysProfile = [Select Id from Profile where name = 'System Administrator'];
User portalOwnerusr = new User(
Firstname='Demo',
Lastname='PortalOwner',
UserRoleId = portalRole.Id,
Email='demo.portalowner@test.com',
Username = 'demo.portalOwner' + System.currentTimeMillis() + '@test.com',
ProfileId = sysProfile.Id,
Alias = 'demalss',
EmailEncodingKey='UTF-8',
LanguageLocaleKey='en_US',
LocaleSidKey='en_US',
TimeZoneSidKey = 'America/Los_Angeles'
);
Database.insert(portalOwnerusr);
return portalOwnerusr;
}


Step 2: Create a Community User


private static User createCommunityUser(User portalOwner) {
User communityUser ;
System.runAs ( portalOwner ) {
//Create account
Account acc = new Account(
Name = 'acc',
OwnerId = portalOwner.Id
);
Database.insert(acc);
//Create contact
Contact con = new Contact(
FirstName = 'conFirst',
Lastname = 'conLast',
AccountId = acc.Id,
Email = 'con' + System.currentTimeMillis() + '@test.com'
);
Database.insert(con);
communityUser = new User(
FirstName = 'DemoFirst',
LastName = 'DemoLast',
Email = 'Democommunityuser@test.com',
ProfileId = [SELECT Id FROM Profile WHERE Name = 'Community User Plus User'].Id,
Username = 'Democommunity.user.' + System.currentTimeMillis() + '@test.com',
Title = 'Title',
Alias = 'DemoAls',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ContactId = con.id
);
Database.insert(communityUser);
}
re



Step 3: call below code from the test method: 

User portalOwner = createPortalAccountOwner();
User portaluser= createCommunityUser(portalOwner);

Thursday 18 April 2024

Salesforce Import and export Files/Attachments

 Salesforce Import and export Files/Attachments


Step 1:  Export files using the below path:  Setup ==> Data ==> Data Export

Select options: 

        Export File Encoding: UTF-8

        Include images, documents, and attachments: Checked

        Include Salesforce Files and Salesforce CRM Content document versions: Checked

        Replace carriage returns with spaces: Checked

 Select Specific objects to get their attachments: Here, I opted Account






Step 2: Download the zip file from Salesforce

Salesforce sends an email once the files are ready to download

 



Step 3: Unzip the downloaded file and navigate to the ContentVersion folder 
             and ContentVersion.csv. add the extension (.pdf, .xlsx, .jpeg, etc.) to any file.

 

Step 4: Create a CSV file with below Header values: 




Step 5: Go to Data loader settings and check both (Read/Write) UTF-8 settings as below:




Step 6: Select the Insert option, search for the content version object, and load the CSV file to upload the attachment.: 



Step 6: Once Upload is completed, Data Loader creates success and error files respectively:


        















Monday 18 March 2024

Salesforce Code Analyzer Command


Salesforce Code Analyzer Command example/Sample


Installing Salesforce code analyzer:

Link: https://forcedotcom.github.io/sfdx-scanner/en/
v3.x/getting-started/install/

Go to VScode -- > New terminal - -> Enter below command
(It installs analyser)
Project location > sfdx plugins:install @salesforce/sfdx-scanner

To check whether the code analyzer is installed or not:

(It checks whether the code analyzer is installed or not)
Project location > sfdx plugins -->

To generate a report Go: to the command prompt

and enter the below command :

(Can generate different reports like .xml, and .csv as well)
Project location > sfdx scanner:run --target "**/default/**"
--outfile results.html


GENERIC COMMAND for Code Scanner

$sfdx scanner:run --target './force-app/main/default/' --projectdir
'./force-app/main/default' --format csv --outfile=codereviewGeneric.csv

CPD Command
$sfdx scanner:run --engine cpd --target './force-app/main/default/'
--projectdir './force-app/main/default' --format csv --outfile=codereviewCPD.csv

DFA Command - Graph Engine (this one takes time to generate report)
$sfdx scanner:run:dfa --target './force-app/main/default/' --projectdir
'./force-app/main/default' --format csv --outfile=codereviewDFA.csv 




reference from : 

https://developer.salesforce.com/docs/platform/salesforce-code-analyzer/guide/dfa.html

https://developer.salesforce.com/docs/platform/salesforce-code-analyzer/guide/cpd-engine.html


Salesforce Code Analyzer Command example/Sample

Wednesday 31 January 2024

Get sObject Name and Permission Set Assignment SOQL in the Salesforce

 Salesforce: Get sObject Name and Permission Set Assignment


SOQL:
SELECT Parent.Name, Parent.PermissionsTransferAnyLead,SobjectType ,PermissionsRead, PermissionsCreate,PermissionsDelete, PermissionsModifyAllRecords, PermissionsViewAllRecords
FROM ObjectPermissions     
WHERE  ParentId in (
            SELECT id
            FROM PermissionSet
            WHERE name IN ( 'Master_Edit_Access'))



            

Thursday 12 October 2023

Error : "Trigger must be associated with a job detail"




My_SchedulerClass sc = new My_SchedulerClass ();
String cronExp2= '0 16 09 * * ? *';
String JobId = system.schedule('Oppy_Scheduled0916 ', cronExp2, sc);


In the above code, there is a white space 'Oppy_Scheduled0916 ', when removed this extra space from the system.schedule ("Oppy_Scheduled0916") my class was scheduled as expected.

Friday 21 July 2023

Salesforce Order Creation using Rest API : Place Order REST API

Salesforce Order Creation using Rest API : Place Order REST API 


@RestResource(urlMapping='/CreateOrder/*')

global with sharing class RestAPiOrderCreation {

    @HttpPost

    global static WrapperClass createOrderOrderItemRestApi() {

        List<OrderItem> orderItemsTempList = new List<OrderItem>();

        WrapperClass responseWrapper = new WrapperClass();

        MAP<String,integer> lineNumberQtyMap = new MAP<String,integer>();

        Set<String> lineItemNumberSet = new Set<String>();

        List<Order> orderList = new List<Order>();

        String orderType;

        List<PricebookEntry> pricebookEntryList = new List<PricebookEntry>();

        Date effectiveDate;

        String errorMessage;

        try{ 

            Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(RestContext.request.requestBody.toString());

            List<object> orderMainlist = (List<Object>)params.get('order');

            for(object obj :orderMainlist){

                Map<String, Object> params2 = (Map<String, Object>)obj;

                order ordInst = new order();

                String effDateStr = (String) params2.get('EffectiveDate'); // **

                ordInst.EffectiveDate = Date.valueOf(effDateStr);

                effectiveDate = Date.valueOf(effDateStr);

                String deliveryDateStr = (String) params2.get('DeliveryDate');

                ordInst.PoNumber = (String) params2.get('PONumber');

                ordInst.Status = 'Draft';

                orderList.add(ordInst);

                List<Object> orderItemsvar = (List<Object>) params2.get('OrderItems');

                for(object objOI : orderItemsvar){

                    Map<String, Object> params3 = (Map<String, Object>)objOI;

                    OrderItem ordItemInst = new OrderItem();

                    ordItemInst.Quantity =Integer.valueOf( params3.get('Qty'));

                    lineNumberQtyMap.put(String.valueOf(params3.get('LineNumber')),Integer.valueOf( params3.get('Qty')));

                    orderItemsTempList.add(ordItemInst);

                    lineItemNumberSet.add(String.valueOf( params3.get('LineNumber')));

                }

            }        

            

            pricebookEntryList = [SELECT id,name,Product2Id,Product2.name,Product2.StockKeepingUnit,UnitPrice,  Pricebook2Id, Pricebook2.name

                                  FROM PricebookEntry  

                                  WHERE 

                                  Product2.StockKeepingUnit  IN : lineItemNumberSet];

            orderList[0].Pricebook2ID  = pricebookEntryList[0].Pricebook2Id;

            orderList[0].status  = 'Draft';

            orderList[0].accountid ='0018d00000fkDsnAAE';

            orderList[0].ContractId ='8008d000000ExAFAA0';

            orderList[0].EffectiveDate =system.today()+10;

            system.debug('===Before orderList=='+orderList);

            if(!orderList.isEmpty()) {

                

                if(Schema.sObjectType.Order.isCreateable()) {

                    insert orderList;

                }

            }

            system.debug('===orderList=='+orderList);

            

            pricebookEntryList = [SELECT id,name,Product2Id,Product2.name,Product2.StockKeepingUnit,UnitPrice,  Pricebook2Id, Pricebook2.name

                                  FROM PricebookEntry  

                                  WHERE 

                                  Product2.StockKeepingUnit  IN : lineItemNumberSet AND Pricebook2Id =: orderList[0].Pricebook2Id ];

            Map<String,PricebookEntry> pbeMap = new Map<String,PricebookEntry>();

            List<OrderItem> orderItemsList = new List<OrderItem>();

           

            for(PricebookEntry pbeInst: pricebookEntryList){

                pbeMap.put(pbeInst.Product2.StockKeepingUnit,pbeInst);

                OrderItem instobj = new OrderItem();

                if(lineNumberQtyMap.containsKey((pbeInst.Product2.StockKeepingUnit)) ){

                    lineNumberQtyMap.get(pbeInst.Product2.StockKeepingUnit);

                    instobj.OrderId = orderList[0].id;

                    instobj.Quantity = lineNumberQtyMap.get(pbeInst.Product2.StockKeepingUnit);

                    instobj.Product2Id =  pbeInst.Product2id;

                    instobj.pricebookentryId =  pbeInst.id;

                    instobj.UnitPrice =  pbeInst.UnitPrice; 

                    orderItemsList.add(instobj);                    

                }

                

            }

            system.debug('===orderItemsList=='+orderItemsList);

            if(Schema.sObjectType.OrderItem.isCreateable()) {

                insert orderItemsList;

            }

        }

        catch (Exception e){

            errorMessage= e.getMessage() +'--getCause'+e.getCause()+'==getInaccessibleFields=='+e.getInaccessibleFields()+'-getLineNumber-'+e.getLineNumber()+'-getStackTraceString-'+e.getStackTraceString();

            responseWrapper.status ='409';

            responseWrapper.message =e.getMessage();

            responseWrapper.sfOrderID ='';

        }  

        

        if(!orderList.isEmpty() &&  String.isEmpty(errorMessage)){

            responseWrapper.status ='200';

            responseWrapper.message ='success';

            responseWrapper.sfOrderID =String.valueof(orderList[0].id);

        }

        else{

            responseWrapper.status ='409';

            responseWrapper.message =errorMessage;

        }

        

        return  responseWrapper;

    }

  

    // Wrapper WrapperClass for return structure 

    

    global class WrapperClass{  

        Public String status {get;set;}

        Public  String message {get;set;}

        Public String sfOrderID {get;set;}

        

    }

 

}


==========================


Success Scenario :

                   











Failure Scenario:






Thursday 27 January 2022

Salesforce: Iterate Map for old and new Value

 Salesforce: Iterate Map for old and new Value


Trigger


trigger Opportunitytrigger on Opportunity (Before Insert,Before Update,After Update) {


   
        //Before Update 
    if(trigger.isBefore && trigger.isUpdate){
        system.debug('--Before Update');
        Opportunitytriggerhandler oOpportunitytriggerhandler = new Opportunitytriggerhandler();
        oOpportunitytriggerhandler.onBeforeUpdate(Trigger.oldMap,Trigger.newMap);
    }
}

                                                                                                                                            
=============================================================
Handler Class

public class  Opportunitytriggerhandler{
    
    
    public void onAfterUpdate(map<id,Opportunity> oldMap,map<id,Opportunity> newMap){
    
 
    
    public void onBeforeUpdate(map<id,Opportunity> oldMap,map<id,Opportunity> newMap){
        OpportunityHelper objHelper = new OpportunityHelper();
        objHelper.checkOpportunityAmount(oldMap,newMap);
    }
   
}

=============================================================


Helper Class

public class OpportunityHelper {
    
    public void checkOpportunityAmount(map<id,Opportunity> oldMap,map<id,Opportunity> newMap){
        for(Opportunity opp:newMap.values()){
            //    Needs Analysis  Qualification
            system.debug('Old AMount '+oldMap.get(opp.id).StageName);
            system.debug('New Map'+newMap.get(opp.id).StageName);
            System.debug('Before Update finish');
            if(oldMap.get(opp.id).StageName !=  newMap.get(opp.id).StageName){
                
                opp.isAmountChanged__c = true;
            }

        }
    }

}

Thursday 26 August 2021

Salesforce MAP with Dynamic Values

Salesforce MAP with  Dynamic Values  

Considerations: 

e.g. Account trigger is passing old and new maps.

Create a custom metadata: ObjectNames_Setting__mdt ,DeveloperName must have object Name



public void dynamicmethod(Map<Id,sobject> newAccountMap, Map<Id,sobject> oldAccountMap) {

       

        Set<Id> resultIds = new Set<Id>();

              

        system.debug('----------'+newAccountMap+'-----'+oldAccountMap+'----------'+newAccountMap.size()+'-----'+oldAccountMap.size());

        try{

            Set<Id> ids = newAccountMap.keySet();

            Id firstId =  new List<id> ( ids )[0];

            String sObjName = firstId.getSObjectType().getDescribe().getName(); //

            system.debug('---DynamicsObjName---'+sObjName); //

            

            List<ObjectNames_Setting__mdt> MOSobj = [SELECT id,Label,Update_Fields_Name__c, FROM ObjectNames_Setting__mdt where DeveloperName =: sObjName   LIMIT 1];

            System.debug('+++'+MOSobj[0].Update_Fields_Name__c);            

            List<String> objectFields = MOSobj[0].Update_Fields_Name__c.split(',');            

            for (sObject l : newAccountMap.values()) {

                //system.debug('=====sObject===='+ l);

                for(String fieldVar : objectFields){

                    if (l.get(fieldVar) != oldAccountMap.get(l.Id).get(fieldVar)) {

                        resultIds.add(l.Id);                    

                        break;

                    } 

                }

  }

}  

 catch(exception e)

        {

            System.debug('--------Exception ---'+e);

}

}

            

Wednesday 5 September 2018

platform developer 2 topics


  • ·         Apex Design pattern
  • ·         Visualforce Developer Guide
  • ·         Lightning Design System Basics.
  • ·         Asynchronous Apex
  • ·         Apex Triggers and Order of Execution
  • ·         When and how to use @future (callout=true)
  • ·         Tools for using metadata in salesforce (Whisper word: Workbench)
  • ·         Best practices in Unit testing (about getURLU especially)
  • ·         Displaying Error messages in Vf pages and in lightning pages
  • ·         Sharing model in Salesforce
  • ·         Apex code Debugging from the sample code (some examples around: Database.rollback )
  • ·         Best practices for Apex CPU time limits
  • ·         Have Apex Governor limits on your fingertips
  • ·         Custom and Standard controllers
  • ·         Using multiple custom controllers and order of execution in the same
  • ·         Ways to view state issues
  • ·         Debugging triggers
  • ·         Exception handling
  • ·         Debugging in Developer Console and its components (refer Salesforce Help Doc here)
  • ·         SOQL and its best practices (especially preventing SQL injection)
  • ·         Types of fields in objects.
  • ·         Unique and External ID fields.
  • ·         Using SOAP/REST web services and its best practices.
  • ·         SOAP API parameters
  • ·         REST annotations
  • ·         Types of APIs in Salesforce and its basics
  • ·         VF pages with Javascript remote actions
  • ·         Dynamic SOQL and its limitations
  • ·         Visualforce tags (Tip: Not the basic tags)
  • ·         List, Set and Map collections in apex
  • ·         Workflows and Process builders (Tip: If process builder is an option in Ans, Think twice. Mostly that would be the ans. Don’t blame me if you get it wrong. )
  • ·         Debugging run time errors from sample code. (Tip: there could be multiple bugs in the code. Look for the line which will cause failure at first in the order of execution)
  • ·         Know about Debug logs and how to debug via debug logs, and setting the parameters for debug logs.
  • ·         Chatter and how apex can access chatter programmatically
  • ·         Pagination in Vf pages and best practices
  • ·         https://developer.salesforce.com/page/Apex_Design_Patterns
  • ·         https://www.youtube.com/watch?v=tsa8Z2S1Agc
  • ·         https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_intro.htm
  • ·         https://trailhead.salesforce.com/modules/lex_dev_lc_basics


Salesforce Sales Cloud Certification Topics and references

Visit to this link





It will redirect you on below link , Use that below link
opt topics from Sales Cloud Basics     and read one by one. It will cover almost all topics

More topics: -