Saturday, December 30, 2023

How TO SENDING SALESFORCE REPORT AS ATTACHMENT

 Here we will show number of ways we can send the report as an attachment in email.

public class ReportsController{

        //Generate report Based on parameter

    public void generateReport(string reportage)

    {

        try

        {

            List <Report> reportList = [SELECT Id,DeveloperName,Name FROM Report where DeveloperName =:reportName];

            if(reportList.size()>0)

            {

                String reportId = (String)reportList.get(0).get('Id');                

                //Get Report Name

                string reportName=(String)reportList.get(0).get('Name');                

                //get SalesForce instance Url

                String instanceName = URL.getSalesforceBaseUrl().toExternalForm();                

                string url=instanceName+'/servlet/PrintableViewDownloadServlet?isdtp=p1&reportId='+reportId;                

                ApexPages.PageReference objPage = new ApexPages.PageReference(url);

                Messaging.SingleEmailMessage email=new Messaging.SingleEmailMessage();               

                Messaging.EmailFileAttachment objMsgEmailAttach = new Messaging.EmailFileAttachment();

                objMsgEmailAttach.setFileName(reportName+'.csv');

                objMsgEmailAttach.setBody(objPage.getContent());

                objMsgEmailAttach.setContentType('text/csv');

                email.setSubject(reportName);                

                List<Messaging.EmailFileAttachment> attach=new List<Messaging.EmailFileAttachment>();

                attach.add(objMsgEmailAttach);

                email.setFileAttachments(attach);  

                 EmailService service=new EmailService(email);

                service.body='Hello, <br/><br/> Here is attached '+reportName+'.<br/><br/>Thank You.<br/>Admin';

                service.isHtml=true;

                service.toAddresses=new List<string>();

                service.toAddresses.add('info@technoeric.com');   

                service.displayName='Technoeric';

                service.subject=reportName;

                service.sendMail();

            }

        }

        catch(Exception ex)

        {

            system.debug(ex.getMessage());

        }

    }

  

}

Friday, December 29, 2023

How To Call Flows From Apex

 

today we are going to make the Flow and call it through apex code and a scheduled class, which calls the controller method to execute the flow.


Step 1: Understanding Flows and Apex

Salesforce Flows automate processes visually, while Apex is used for complex logic. Integrating them allows for more dynamic and powerful automation in Salesforce.

Step 2: Creating a Flow

  • Navigate to Flow Builder: In Salesforce, go to Setup > Process Automation > Flows.
  • Create a New Flow: Choose a flow type suitable for your use case, like Record-Triggered or Auto-Launched.
  • Design the Flow: Add elements such as decisions, assignments, and actions. For instance, create a flow that sends an email when a new lead is added.

Step 3: Preparing Apex Code

  • Open Developer Console: In Salesforce, navigate to the Developer Console.
  • Create a New Apex Class: Name it, for example, FlowController.
  • Import Namespaces: Use System.Flow statements to import necessary namespaces.
public class FlowController {
    // Class content goes here
}

4. Calling the Flow from Apex

  • Instantiate the Flow: In your Apex class, instantiate the Flow using System.Flow.Interview.
public class FlowController {
    public void callFlow() {
        // Set up Lead record as an example
        Lead l = new Lead(FirstName = 'Sapna', LastName = 'Chandani', Email = 'sapna.chandani@example.com', Phone = '8522256355', MobilePhone = '876545465', Company = 'ExampleCompany');
        insert l;
        
        // Prepare the Flow variables
        Map<String, Object> params = new Map<String, Object>();
        params.put('newLead', l);
        
        // Instantiate and start the Flow
        Flow.Interview.Your_Flow_Name yourFlow = new Flow.Interview.Your_Flow_Name(params);
        yourFlow.start();
    }
}
  • Ensure to replace Your_Flow_Name with the actual name of your Flow.
  • Schedulable Class: For automating the flow execution at scheduled intervals.
global class scheduledFlow implements Schedulable {
    global void execute(SchedulableContext sc) {
        FlowController fc = new FlowController();
        fc.callFlow();
    }
}

How to HANDLE HEAP SIZE By APEX CODE OPTIMIZATION


Load size is how much memory expected to store the different articles, factors, and condition of the Summit exchange in memory. This size is covered at 6MB for simultaneous activities and is multiplied to 12 MB for offbeat cycles. In the event that the size is expanded past this covered size, we get the mistake "Apex size excessively huge". This post will drill down ways of dealing with Heap size for Apex code advancement.


 1. Bring just required records

In the above model, we are returning the total request list utilizing SOQL which probably won't be needed. Utilize some channel models so that main required records will be gotten. in the event that we have less records, it will take lesser memory.


We can utilize customerid as a channel standards which will channel records and will diminish heap size. Look at our other post Use Channel in SOQL for the advantages of sifting records.


2. Get just required fields

In the above model, we have brought such countless fields yet we are not utilizing a large portion of them in the code. That multitude of gotten fields will find opportunity to recover from the data set and will hold memory also when saved in any factor like requests in the above model.


We ought to just get the necessary fields from the data set. It will lessen the possibilities of Heap size mistakes in addition to the code will work quicker too.


3. Use for circle for SOQL

In the above model, we have performed gotten information from the data set and saved total information in orders variable. This variable is utilized exclusively in for circle and there could be no other use. We can stay away from such sort of SOQL and on second thought of this, we can straightforwardly utilize it in for circle.


List<string> orderNumbers=new List<string>();

for(AcctSeedERP__Sales_Order__c ord:[Select id,AcctSeedERP__Customer__r.Name from AcctSeedERP__Sales_Order__c])

{

    orderNumbers.add(ord.Name);

}

system.debug( 'Stack Status ' + (limits.getHeapSize()>limits.getLimitHeapSize()));

system.debug( ': Stack size is ' + limits.getHeapSize() + ' upheld is ' + limits.getLimitHeapSize());

view rawHeapIssueFix.apxc facilitated with ❤ by GitHub

One more significant advantage of involving SOQL in for circle is it will be getting just 200 records in one go and this manner SOQL limit exemptions won't be tossed. So utilize this idea any place you can apply it in zenith code. I have eliminated all unused fields in the above model too, this will likewise diminish memory size.


4. Stay away from system.debug

Stay away from the System.Debug in code. It can make issues underway. Checkout our other post for Enhance Code by Impairing Troubleshoot Mode


5. Stay away from class-level factors and utilize neighborhood variable

Keep away from class-level factors as they will be put away in memory until the total exchange for that class isn't done. It will be smarter to utilize a nearby factor that will consequently deliver after that block execution.


6. Rather than a major strategy utilize more modest techniques

According to best practice, we ought to make more modest techniques around 20 lines. We ought to keep away from greater techniques as they will make intricacy and reliance in code. A variable made in the strategy will be alive till the technique execution so in the event that we have more modest strategies, the variable will be cleaned early soon after strategy execution so our store size will have more space to hold different items.


On account of a greater technique, the variable will be in the load until the total strategy isn't executed, it will take some space and may be a justification for the store size special case. So better will make more modest strategies.


7. Free memory when not being used

Any place we are utilizing objects to store information, attempt to eliminate them from memory following use. We shouldn't pass on everything for the framework to clean. Make a training to clean it right away and free some memory from the store. This will help in putting away different information for usefulness. In the above model, we have an orders variable that can be cleaned after for circle. Dole out invalid to clean object memory.


8. Utilize Asynchronous Techniques

Some of the time we really want to do a few weighty tasks and it could have to utilize a lot of memory, all things considered, we can utilize nonconcurrent strategies so the store size will be expanded to 12MB and we can finish our pinnacle exchange. We can utilize Future callouts, queueable strategies, or bunch occupations in light of the prerequisite. We can utilize this methodology for callout, document dealing with, and so on.

How to download the developer console SOQL query results

 

Hi Friends today we are going to discuss, How to download the developer console  SOQL query results


Step 1: activate user select

enter image description here

Step 2: select results

enter image description here

Step 3: copy & paste it to excel

enter image description here

Saturday, December 16, 2023

Query Optimization Salesforce

 

Query optimization in Salesforce refers to the process of improving the performance and efficiency of your Salesforce queries. Salesforce uses a language called SOQL (Salesforce Object Query Language) for querying data. Here are some tips for optimizing your queries in Salesforce:

1.     Indexing:

·        Ensure that the fields used in WHERE clauses are indexed. Indexing allows Salesforce to quickly locate the records that match the specified conditions.

·        Standard fields are generally indexed, but custom fields may need to be manually indexed.

2.     Selective Filtering:

·        Design your queries to be selective. Selective queries are those that filter out a large portion of the records, allowing Salesforce to quickly retrieve the relevant data.

·        Avoid using "LIKE" queries without a leading wildcard ('%') as they are not selective and can result in full table scans.

3.       Query Plan Tool :

·        The Query Plan tool in the Developer Console can help speed up SOQL queries done over large volumes. Use the Query Plan tool to optimize and speed up queries done over large volumes.

4.     Limit the Number of Records Returned

·        Use the LIMIT clause to restrict the number of records returned by a query. This can significantly improve performance, especially when dealing with large datasets.

5.     Avoid Using "NULL" in WHERE Clauses:

·        Queries that include "IS NULL" or "IS NOT NULL" conditions can be less performant. Try to avoid these conditions if possible.

6.     Bulkify Your Code:

·        When writing triggers or batch processes, make sure your code can handle bulk data processing. Avoid using SOQL or DML statements inside loops to prevent hitting governor limits.

7.     Use Aggregate Queries Wisely:

·        Aggregate queries (e.g., using GROUP BY) can be resource-intensive. Use them judiciously and ensure that the fields you are aggregating are indexed.

8.     Query Plan Tool:

·        Use the Query Plan tool in the Developer Console to analyze the query performance. It helps you understand how Salesforce executes your query and identify any potential bottlenecks.

9.     Consider External Objects:

·        For large datasets that are not suitable for traditional Salesforce queries, consider using External Objects and External Data Sources to query data stored outside Salesforce.

10. Review Query Optimizer Warnings:

·        When running a query in the Developer Console, pay attention to any query optimizer warnings. These warnings provide insights into potential performance issues.

11. Use SOQL Best Practices:

·        Familiarize yourself with SOQL best practices outlined in the Salesforce documentation. This includes understanding query syntax, using relationships efficiently, and optimizing queries for performance.

 


 

Thursday, December 14, 2023

Salesforce exceptions and possible solutions

 Salesforce, being a complex platform, can encounter various exceptions or errors. Here are some common Salesforce exceptions and possible solutions:

  1. NullPointerException:

    • Cause: Trying to access or manipulate an object that is null.
    • Solution: Ensure that the object is initialized before performing any operations on it. Use conditional statements to check for null values.
  2. QueryException:

    • Cause: Issues with SOQL (Salesforce Object Query Language) queries.
    • Solution: Verify the syntax of your SOQL query. Ensure that field names, object names, and relationships are accurate. Also, be mindful of governor limits related to queries.
  3. DMLException:

    • Cause: Errors during Database Manipulation Language operations (insert, update, delete, undelete).
    • Solution: Wrap DML operations in try-catch blocks to catch exceptions. Check for validation rules, triggers, and workflow rules that might be causing the issue.
  4. LimitException:

    • Cause: Exceeding governor limits imposed by Salesforce.
    • Solution: Review and optimize your code to avoid hitting limits. Use asynchronous processing, bulk processing, and implement best practices to minimize resource consumption.
  5. CalloutException:

    • Cause: Errors during web service callouts.
    • Solution: Ensure that the external service is reachable and the request format is correct. Handle exceptions and implement retry mechanisms for callouts.
  6. Apex CPU Time Limit Exceeded:

    • Cause: Apex code exceeding the CPU time limit.
    • Solution: Optimize your code, use bulk processing, and consider moving complex operations to asynchronous processing (such as batch Apex or future methods).
  7. System.LimitException: Too many SOQL queries: 101:

    • Cause: Exceeding the limit of 100 SOQL queries in a single transaction.
    • Solution: Optimize your code to reduce the number of queries. Consider using relationships and aggregate queries to retrieve data more efficiently.
  8. System.QueryException: Non-selective query against large object type:

    • Cause: Performing a non-selective query on a large object.
    • Solution: Index fields used in WHERE clauses to make queries selective. Consider using custom indexing for large objects.
  9. System.DmlException: Insert failed: FIRST_EXCEPTION: ...:

    • Cause: Validation rule, trigger, or workflow rule preventing the record from being inserted.
    • Solution: Identify and address the issue in your validation rules, triggers, or workflow rules that is blocking the record insertion.
  10. System.AsyncException: Future method cannot be called from a future or batch method:

    • Cause: Trying to call a future method from another future method or batch method.
    • Solution: Ensure that you are not making asynchronous calls from within asynchronous methods. Restructure your code to avoid such scenarios.