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: -


Thursday, 17 May 2018

Create Super Clone Button To clone 3 level of Hierarchy


Create Super Clone Button To clone 3 level of Hierarchy :

Object Schema 


Create JavaScript Button on Account Detail page :


{!REQUIRESCRIPT("/soap/ajax/19.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}

try{
alert("Entered try");
var accId='{!Account.Id}';
alert('____1___'+accId);
sforce.apex.execute("superClone","createClone",{accId:accId});
alert('____2___'+accId);
txt="Clones Create";
alert(txt);
}
catch(err) {
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.description + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}

Apex class Code :Class Name superClone 


global class superClone {
    
    static Map<Id,Id> newoldcon=new Map<Id,Id>();
    webservice static void createClone(String accId)
    {
        system.debug(accId);
        Account acc= [SELECT ID, Name FROM Account WHERE Id = :accId];
        system.debug(acc);        
        Account acccopy=acc.clone(false,true);
        acccopy.Name=acc.Name+'Clonedcopy';
        insert acccopy;  // Grand Parent
        
        List<Contact> con = [SELECT Id, LastName, AccountId FROM Contact WHERE AccountId = : acc.Id];
        List<Contact> consdup= new List<Contact>(); 
        List<Id> cid = new List<Id>();
        if(con!=null)
        {
            for(Contact c:con)
            {
                cid.add(c.Id);
                Contact concopy=c.clone(false,true);
                concopy.AccountId=acccopy.Id;
                concopy.LastName =c.LastName + 'clonecopy';
                consdup.add(concopy);
            }
        }
        Database.insert(consdup);  // Parent
      
        if(consdup!=null && cid!=null)
        {
             for(ID i:cid)
            {
            for(Contact c1:consdup)
            {
                newoldcon.put(i,c1.id);
                
            }
            //createDivCon(i);
       
            } 
        }
        System.debug('newoldcon++++++ old id '+newoldcon.keySet());     
        List<Divsional_Contact__c> divlist=[SELECT Id,Name,Contact_Parent__c FROM Divsional_Contact__c WHERE Contact_Parent__c=:newoldcon.keySet()];
       System.debug('divisional list-------------******'+divlist);
        List<Divsional_Contact__c> divlist1=new List<Divsional_Contact__c>();
        if(divlist!=null)
        {
            for(Divsional_Contact__c d: divlist)
        {
             Divsional_Contact__c divcopy=d.clone(false,true);
            divcopy.Contact_Parent__c=newoldcon.get(d.Contact_Parent__c);
            divcopy.Name=d.Name+'Cloned Copy';
            divlist1.add(divcopy);
        }
        }  System.debug('--------------- ++++++divlist1 list'+divlist1);
           Database.insert(divlist1); 
       
        
    }



}

Credits goes to @Preeti

Monday, 16 April 2018

Salesforce Service Cloud Certification Topics


  • Industry Knowledge: 66%
  • Implementation Strategies: 54%
  • Service Cloud Solution Design: 33%
  • Knowledge Management: 50%
  • Interaction Channels: 20%
  • Case Management: 42%
  • Contact Center Analytics: 0%
  • Integration and Data Management: 100% 
  • --------------------------
  • omni channel salesforce
  • Quick Text
  • Macros
  • Publisher action
  • Live Agents
  • Chatter questions
  • Entitlement implement
  • Enable Salesforce social profile on contacts
  • SOS Video Chat
  • Developer k pro sandbox
  • Set up milestones
  • Enable HISTORY component within the Salesforce console for service
  • An Enterprise resource planning system
  • Milestones
  • Add the question action to chatter in the community publisher
  • Live agent user profile
  • Field Service Lightning
  • On demand email to Case

Friday, 28 July 2017

Salesforce Jenkins Ant deployment Steps

/**********************************************************************

**********************************************************************/


PREREQUSITES
*************************************************
1. JDK
2. JRE
3. Force.com Migration tool
4. Apache Ant

*************************************************

A. Install ANT
*************************************************
Step 1: Download JRE 6 : Verify the correct installation by executing the following command: java -version
Step 2: Download Ant(version 1.6 or higher) zip file from http://ant.apache.org/bindownload.cgi
Step 3: Download Force.com Migration Tool zip folder from Salesforce Org for which the path is as follows: Develop->Tools->Force.com Migration Tools
Step 4: Copy the "ant-salesforce.jar" file from the above extracted folder and paste it in the lib directory of the installed Ant folder.
Step 5: Set the environment Variables as follows:
        ->System Variables->new>  Variable Name: ANT_HOME
                         Variable Value: C:\Program Files\apache-ant-x.xx.x
->System Variables->new>  Variable Name: JAVA_HOME
                         Variable Value: C:\Program Files\Java\jdk_x.xx.x

        ->System Variables->edit->PATH ->
                                  In PATH, add %JAVA_HOME%\bin and %ANT_HOME%\bin
..... %SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;....;%JAVA_HOME%\bin;%ANT_HOME%\bin; .....

Step 6: Verify if 'C:\Program Files\Java\jdk_x.xx.x\lib' contains 'Tools.jar' file.
Step 7: Run the following command in cmd to verify the correct installation of ANT : ant -version

OPTIONAL:
Step 8: have build.xml and build.properties at the src level of moving source file.(ANT checks package.xml of the project src file to know what all things have to migrate).


*************************************************

B. Install Jenkins (on Windows)
*************************************************
If you're running on Windows you might want to run Jenkins as a service so it starts up automatically without requiring a user to log in. Install jenkins using windows package (http://jenkins-ci.org/) or using java web archive (.war) file.
You need to start jenkins engine if you've installed using the .war file. To do this, open command prompt and navigate to the folder where 'jenkins.war' file is located. run the following command:

C:/...>java -jar jenkins.war

If you've installed using windows installer, there's no need to start jenkins engine.
To run Jenkins, open your browser and connect to 'localhost:8080'



*************************************************

C. Configure Jenkins
*************************************************
Once your jenkins is up, goto jenkins > manage jenkins > configure system
Update the JDK and ANT sections with their respective version and path.



*************************************************

D. Configure Jobs
*************************************************
1. Click on 'New Item' and enter item name. Select 'free-style software project'. click 'OK'
2. Goto 'Build' section in the configuration page. Select Ant version.
3. In the Targets field, enter the library and property file path.
Eg:
-lib
D:\...\apache-ant-1.9.2\lib/ant-salesforce.jar
-propertyfile
D:\...../build.properties

4. Click on advanced button. In the 'Build File' field, enter the the path Ant's for build.xml
D:\.....\build.xml

5. In the 'Proprties' field, enter the salesforce parameters used by Ant in build.xml

sf.username = user@xyz.com
sf.password = PasswordSecurityToken
sf.serverurl = login.salesforce.com
sf.checkOnly = false
sf.runAllTests = false
sf.logLevel = None

6. Click Save. Your deployment job is ready to go! Click 'Build Now' to run the deployment job.
*************************************************