New Batch#100 (10th Nov 2021) - Salesforce Admin + Dev Training (WhatsApp: +91 - 8087988044) :https://t.co/p4F3oeQagK

Showing posts with label apex. Show all posts
Showing posts with label apex. Show all posts

Sunday, 16 June 2013

Map usage in Apex

Map usage in APEX:

public with sharing class MapUsage {
        
        public static void mapUse(){
        
            Map<Integer, String> mp = new Map<Integer, String>();
            // kEy is Integer
            // value is String
            
            mp.put(1221,'Mahi');
            //mp.put(1226,'Shyam');
            mp.put(1211,'Rajesh');
            mp.put(1255,'Kiran');
            
            System.debug('---------------Elements in the map are ------------>'+mp);
            System.debug('---------------Size of the map is-------4---------->'+mp.size());
            System.debug('------------Keys in the map are ----------->'+mp.keyset());
            System.debug('------------Values in the map are ----------->'+mp.values());
            
            System.debug('------------------'+mp.get(1211));
            
            mp.remove(1226);
            
            mp.put(1211,'Charan');
            mp.put(1248,'Pavan');
            mp.put(1222,'Kiran');
            
            System.debug('---------------Elements in the map are ------------>'+mp);
            System.debug('---------------Size of the map is-------5---------->'+mp.size());
            
            for(Integer i : mp.keyset()){
                System.debug('-----Key--------'+i);
                System.debug('-----value---------'+mp.get(i));
            }
            
            for(String s: mp.values()){
                System.debug('----------------'+s);
            }
            
        }        
}

Set usage in Apex

Set usage in APEX:

public with sharing class SetUsage {
    
    public void setUse(){
        
        Set<Integer> st = new Set<Integer>();
        
        st.add(1234);
        st.add(1248);
        st.add(1225);
        st.add(1252);
        
        System.debug('----------------Elementa in the set are --------------'+st);
        System.debug('----------------Size of Elementa in the set are ------4--------'+st.size());
        
        st.remove(1252);
        System.debug('----------------Size of Elementa after removing an element in the set are ------3--------'+st.size());
        
        
        st.add(1248);
        st.add(1252);
        st.add(1221);
        System.debug('----------------Size of Elementa in the set after adding duplciates are ------5--------'+st.size());      
        
        Set<Integer> newst = st.clone();
        System.debug('----------------Size of Elementa in the new set are -------5-------'+newst.size());
        
        st.clear();
        System.debug('-----------------NEw set is EMpty or not--------false--------'+newst.isEmpty());
        
        for(Integer i: newst){
            System.debug('----------------->'+i);
        }        
    }
    
}

List usage in Apex

List Usage in APEX:

public with sharing class ListUsage {
        
        public void listUse(){
            
            // Initialising a list
            List<String> lst = new List<String>();
            
            // Adding elemenst into list
            lst.add('ABC');
            lst.add('DEF');
            lst.add('GHI');
            lst.add('JKL');
            
            System.debug('---------Elements in the list are-------------->'+lst);
            System.debug('----------Size of the Elements are-----4-------->'+lst.size());
            System.debug('-----------Element in 2nd index--------GHI-------->'+lst[2]);

            lst.remove(1);
            System.debug('---------Elements in the list after removing are-------------->'+lst);
            System.debug('----------Size of the Elements after removing are----3--------->'+lst.size());
            
            lst.add('MNO');
            lst.add('GHI');
            lst.add('DEF');
            lst.add('1248');
            
            System.debug('---------Elements in the list after adding duplicate values are-------------->'+lst);
            System.debug('----------Size of the Elements after adding duplicate values are--------7----->'+lst.size());
            
            List<String> newlst = lst.clone();
            System.debug('---------Elements in the new list are-------------->'+newlst);
            System.debug('----------Size of the Elements in new list are-------7------>'+newlst.size());
            
            lst.clear();// removes all the elements in the list
            System.debug('-----------------List is Empty or not-------true----------->'+lst.isEmpty());
            System.debug('-----------------New List is Empty or not-------false----------->'+newlst.isEmpty());
            
            //Indexing for loop 
            for(integer i=0; i<newlst.size(); i++){
                System.debug('-----Index------->'+newlst[i]);
            }
            
            //For Each Loop
            for(String s: newlst){
                System.debug('-----For Each---------->'+s);
            }
            
            
        }
        
        
        
}

Sunday, 3 February 2013

Difference between Interface and Abstract Class


Interface
Abstract Class
Declare with keyword Interface
Declare with keyword Abstract
It will not contain constructor
It may or may not contain constructor
By default all methods are public abstract methods.
It contains abstract methods and non abstract methods.
It contains only final variables
It contains final variables and instance variables
We can implement multiple interfaces
We can inherit only one abstract class

Wednesday, 16 January 2013

how to lock a record?

To lock a set of sObject records in Apex, embed the keywords FOR UPDATE after any inline SOQL statement

Tuesday, 2 October 2012

Using Batch Apex to Change the Account Owners


global class AccountOwnerReassignment implements 
             Database.Batchable<SObject>, Database.Stateful{
    
    User fromUser{get; set;}
    User toUser{get; set;}
    Double failedUpdates{get; set;}
    //Parameter Construcotr
    global AccountOwnerReassignment(User fromUser, User toUser){
        this.fromUser = fromUser;
        this.toUser = toUser;
        failedUpdates = 0;
    }
    
    global Database.queryLocator 
                    start(Database.BatchableContext ctx){
        return Database.getQueryLocator([SELECT id, name, ownerId 
                        FROM Account WHERE ownerId = :fromUser.id]);
    }
    
    global void execute(Database.BatchableContext ctx, List<Sobject> scope){
        List<Account> accs = (List<Account>)scope;
        
        for(Integer i = 0; i < accs.size(); i++){
            accs[i].ownerId = toUser.id;
        }
        
        List<Database.SaveResult> dsrs = Database.update(accs, false);
        for(Database.SaveResult dsr : dsrs){
            if(!dsr.isSuccess()){
                failedUpdates++;
            }
            
        } 
    }
    
    global void finish(Database.BatchableContext ctx){
    
        AsyncApexJob a = [SELECT id, ApexClassId, 
                       JobItemsProcessed, TotalJobItems, 
                       NumberOfErrors, CreatedBy.Email 
                       FROM AsyncApexJob 
                       WHERE id = :ctx.getJobId()];
        
        String emailMessage = 'Your batch job '
             + 'AccountOwnerReassignment '
             + 'has finished.  It executed ' 
             + a.totalJobItems 
             + ' batches.  Of which, ' + a.jobitemsprocessed 
             + ' processed without any exceptions thrown and ' 
             + a.numberOfErrors +
             ' batches threw unhandled exceptions.'
             + '  Of the batches that executed without error, ' 
             + failedUpdates 
             + ' records were not updated successfully.';
        
        Messaging.SingleEmailMessage mail = 
              new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.createdBy.email};
        mail.setToAddresses(toAddresses);
        mail.setReplyTo('noreply@salesforce.com');
        mail.setSenderDisplayName('Batch Job Summary');
        mail.setSubject('Batch job completed');
        mail.setPlainTextBody(emailMessage);
        mail.setHtmlBody(emailMessage);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] 
                           { mail });
    }    
}
In Developer Console Paste below code:

User fromUser = [select id,firstname from user where firstname = 'name of the user'];
User toUser = [select id,firstname from user where firstname = 'name of the user'];                 
Database.executeBatch(new AccountOwnerReassignment(fromUser,toUser));
Note: Name of the user means, Goto Managed Users>Click on particuar user> At the top below the User one name will display that name we should give in place of 'name of the user'

Calling Batch Apex from Trigger:
* Goto App Setup> Customize> Account> Triggers

Trigger AccountOwnerReassignment on Account (before insert) {
    List<Account> al = Trigger.new;
    for(Account a:al) {
        User fromUser = [select id,firstname from user where alias = 'alias name'];
        User toUser = [select id,firstname from user where alias = 'alias name'];                 
        try {
            Database.executeBatch(new AccountOwnerReassignment(fromUser,toUser));
        }
        Catch(Exception E) {
        }
    }
}
Note: In case, no rows queried from the SOQL Queries below error will arise.
Error: Invalid Data. Review all error messages below to correct your data.Apex trigger AccountOwnerReassignment caused an unexpected exception, contact your administrator: AccountOwnerReassignment: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.AccountOwnerReassignment: line 4, column 1

Refer:
http://developer.force.com/cookbook/recipe/using-batch-apex-to-reassign-account-owners

Wednesday, 12 September 2012

Annotations

Annotations:
* An Apex annotation modifies the way a method or class is used, similar to annotations in Java.
* Annotations are defined with an initial @ symbol, followed by the appropriate keyword.
* To add an annotation to a method, specify it immediately before the method or class definition.
global class MyClass {
     @future
     Public static void myMethod(String a)
     {
          //long-running Apex code    
     }
}
Annotations supported by Apex
Annotation Name
Description
@Deprecated
* Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces or variables that can no longer be referenced in subsequent release of the managed package in which they reside.
* This is useful when you are refactoring code in managed package as the requirements evolve.
* New subscribers cannot see the deprecated elements, while the elements continue to function for existing subscribers and API integrations.
Syntax:
@deprecated
//This method is deprecated, use myOptimizedMethod(String a, String b) instead
Public void myMethod(String a) {
}

@Future

@IsTest

@ReadOnly

@RemoteAction


Latest Versions in SFDC



Name
Latest Version
Apex Data loader
29.0
Force.com API
29.0
Force.com IDE
29.0.0 (compatible with Eclipse 4.2 and 4.3)
Salesforce.com
Winter' 2014


Tuesday, 11 September 2012

Upsert

* upsert sObject​​ opt_external_id
* opt_external_id​​ is an optional variable that specifies the custom field that should be used to match records that already exist in your organization's data
How Upsert Chooses to Insert or Update
Upsert uses the sObject record's primary key (or the external ID, if specified) to determine whether it should create a new object record or update an existing one:
  • If the key is not matched, then a new object record is created.
  • If the key is matched once, then the existing object record is updated.
  • If the key is matched multiple times, then an error is generated and the object record is neither inserted or updated.


Refer:
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dml_upsert.htm

Labels