Posts

Showing posts from March, 2023

Get my org’s url using Salesforce Formula field (Text Type)

  Get my org’s url: The $Api.Partner_Server_URL_530 variable returns the endpoint of your Salesforce org. This formula is saying “Starting from the left of the entire URL, return the characters all the way until the position of “/services”. LEFT({!$Api.Partner_Server_URL_530},FIND("/services", {!$Api.Partner_Server_URL_530}))

number of Saturdays between those 2 dates. Create formula field

FLOOR(( End_Date__c -  Start_Date__c )/7) + IF(OR (WEEKDAY(Start_Date__c )=7, WEEKDAY(End_Date__c )=7, WEEKDAY(Start_Date__c )>WEEKDAY(End_Date__c )),1,0) If you want the number of Sundays: FLOOR(( End_Date__c -  Start_Date__c )/7) + IF(OR (WEEKDAY(Start_Date__c )=1, WEEKDAY(End_Date__c )=1, WEEKDAY(Start_Date__c )>WEEKDAY(End_Date__c )),1,0) This is easily changed for any day of the week. You only need to change the "WEEKDAY" number (1 for Sunday, 2 for Monday, 3 for Tuesday, etc) in this part: WEEKDAY(Start_Date__c )=1, WEEKDAY(End_Date__c )=1

What is Saml and Oauth and Authentication flow in salesforce

Difference between SAML and OAuth Overview of SAML 1. The user makes a request to Force.com for a specific resource. 2. Force.com detects the user needs to authenticate and redirects the user to their SAML Identity Provider. 3. The user accesses their IdP and authenticates. 4. Once authenticated, the IDP sends a SAML Response back to Salesforce.com. 5. Force.com processes the SAML assertion and logs the user in. Overview of OAuth 1. The OAuth Client makes an authorization request. 2. The Authorization Server authenticates the user. 3. The user authorizes the application. 4. The application is issued an OAuth token. Difference between Web server OAuth flow, User agent flow OAuth Authentication flow and Username-Password OAuth Authentication flow Web server OAuth flow  Typically used for web applications where server-side code needs to interact with Force.com APIs on the user’s behalf, for example DocuSign. Trust that the web server is secure to protect the consumer secret. Client applic

Dynamic SOQL based on Sobject Name and Where Clause

 public class DynamicSOQLUtil {     // Returns a dynamic SOQL statement for the whole object, based on object name and where clause as a dynamic     public static string getCreatableDynamicFieldsSOQL(String objectName, String whereClause){                  String selects = '';         // Check whereclause if null then return null         if (whereClause == null || whereClause == ''){ return null; }                  // Get a map of field name and sobject field         Map<String, Schema.SObjectField> objFieldMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap();         list<string> selectFields = new list<string>();                  if (objFieldMap != null){             for (Schema.SObjectField objFt : objFieldMap.values()){ // loop through all field tokens                 Schema.DescribeFieldResult fd = objFt.getDescribe(); //field describe  for each field                //if (fd.isCreateable()){ // if needed onl

Get fields in SOQL from FIeldSet

global class BatchclassName implements Database.Batchable<sObject>, Database.Stateful, Database.AllowsCallouts{       global Database.QueryLocator start(Database.BatchableContext bc) {         return gAllRecords();     public Database.QueryLocator gAllRecords(){      try{ //Create fieldset on Object and get fields in SOQL query, BankFieldSet this fieldset name on bank object String queryString = 'Select Id'; for(Schema.FieldSetMember fieldMember : sObjectType.Bank__c.FieldSets.BankFieldSet.getFields()){ queryString += ', '+fieldMember.getFieldPath();} system.debug('queryString@@@'+queryString); queryString+=' FROM Bank__c WHERE isActive__c =true AND Location__c=\'Noida\' AND IsNeeded__c= true AND Status__c IN (\'Failed\',\'Unsuceess\') LIMIT '+Integer.valueOf(Label.LabelName); return Database.getQueryLocator(queryString); }catch(Exception ex){ ErrorLog__c log = new ErrorLog__c(); log.Message

In Schedule class run next job from configuration level

global class Schedularclassname implements Schedulable {   global void execute(SchedulableContext SC) {        List<AsyncApexJob> jobs = new List<AsyncApexJob>(); Id thisClassId = [SELECT Id, Name FROM ApexClass WHERE name = 'BatchClassName' LIMIT 1].Id; //Setup Custom Setting Schedular_Settings__c store the time and no of record process in batach class  //Scheduled_Time__c  store time when next batch will run //Schedular_Records__c add batch size how many record will process Schedular_Settings__c objschedule = Schedular_Settings__c.getInstance('Schedular'); if(objschedule!=null && objschedule.Scheduled_Time__c != null && objschedule.Schedular_Records__c != null){ jobs = [select id from AsyncApexJob where (status = 'Processing' OR status = 'Holding' OR status = 'Queued' OR status = 'Preparing') AND ApexClassId = :thisClassId AND JobType = 'BatchApex']; if(jobs == null  || jobs.size()

Get Last day of Month

Get Last day of a month (28, 29, 30 or 31)? Formula DAY(ADDMONTHS(DATE(YEAR(DateField__c), MONTH(DateField__c),1),1)-1) The trick here is to take the 1st of the month and year of the date field, add 1 month to it and subtract 1 day. For example, if my date field is March 3rd 2022, the formula will add 1 month to March 1st 2022 and will return April 1st 2022. We then subtract 1 day to get March 31st 2022.

Generate Random String

 DateTime currentDate = DateTime.now(); String randstring = currentDate.format('ddMMHHmmss'); Integer randomNumberToAppend = null; while(true){     randomNumberToAppend = Integer.valueOf(Math.random()*10000);     if(String.valueOf(randomNumberToAppend).length()==4){         break;     } } randstring += randomNumberToAppend; System.debug('randstring@@@'+randstring);

WAT if the owner of an account is changed then the owner of the related contacts should also be updated.

 Account Trigger ============================================ trigger AccountTrigger on Account (after update) {   Set<ID> accountId = new Set<ID>();   if(Trigger.IsAfter && Trigger.IsUpdate){     for(Account objAcc : trigger.new){       if(trigger.oldMap.containsKey(objAcc.id)){         if(trigger.oldMap.get(objAcc.id).OwnerId != objAcc.OwnerId){           accountId.add(objAcc.Id);         }       }     }     if(accountId != null && accountId.size() > 0 ){       AccountTriggerHandler.UpdateOwnerofContact(Trigger.newMap, accountId);     }   } } ============================================ AccountTriggerHandler Class public with sharing class AccountTriggerHandler {   public static void UpdateOwnerofContact(Map<Id,Account>accountMap,Set<id>accountId){     List<Contact> lstUpdateOwnerofContact = new List<Contact>();     Map<id,Contact> mapofIdToContact = new Map<id,Contact>([SELECT Id,Name,AccountId From contact WHERE Acc

Get Interface Class List from SOQL

ApexTypeImplementor Object: Get the list of all classes which implement a particular interface with the help of ApexTypeImplementor object. List<ApexTypeImplementor> lstofbatchclass =[SELECT Id,ClassName FROM ApexTypeImplementor WHERE InterfaceName = 'Batchable']; https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_apextypeimplementor.htm