Friday 11 April 2014

XML Parsing using DOM Parser in salesforce

Apex Class
  1. public class XMLParsing{
  2.  
  3.   Public void parseXML(String xmlfile)
  4.   {
  5.        DOM.Document xmlDOC = new DOM.Document();
  6.        xmlDOC.load(xmlfile);
  7.        DOM.XMLNode rootElement = xmlDOC.getRootElement();
  8.        System.Debug('$$$$ Root Element'+rootelement);
  9.        
  10.        for(DOM.XMLNode xmlNodeObj:xmlDOC.getRootElement().getChildElements()){
  11.        
  12.        System.Debug('$$$ Child Elements'+xmlNodeObj);
  13.        for(DOM.XMLNode xmlNodeObjChild:xmlNodeObj.getChildren())
  14.        {
  15.        System.Debug('$$$ Childrens'+xmlNodeObjChild.getChildren());
  16.        
  17.              if(xmlNodeObjChild.getName()=='FirstName')
  18.              System.Debug(xmlNodeObjChild.getText());
  19.              if(xmlNodeObjChild.getName()=='Email')
  20.              System.Debug(xmlNodeObjChild.getText());
  21.              if(xmlNodeObjChild.getName()=='Phone')
  22.              System.Debug(xmlNodeObjChild.getText());
  23.              if(xmlNodeObjChild.getName()=='ReasonforContactString')
  24.              System.Debug(xmlNodeObjChild.getText());
  25.          
  26.             }
  27.              
  28.        }
  29.   }
  30.  
  31.  
  32. }

Test Class

  1. @isTest
  2. public class TestXMLParser
  3. {
  4.   static testMethod void testXmlParser() {
  5.  
  6.     XMLParsing a=new XMLParsing();
  7.     String str = '<AptiLeads><lead><FirstName>Arunkumar</FirstName><LastName>R</LastName><Email>arun@gmail..com</Email><Phone>7777777777</Phone><ReasonforContact>Associate of Arts in Business</ReasonforContact></lead><lead><FirstName>Balaji</FirstName><LastName>Ram</LastName><Email>ram@gmail.com</Email><Phone>999999991</Phone><ReasonforContact>Associate of Arts in Busines1s</ReasonforContact></lead></AptiLeads>';
  8.     a.parseXML(str);
  9.  
  10.    }
  11. }

Thursday 3 April 2014

Best Apex Test Class Example for Beginners in Salesforce

Trigger :

  1. trigger RestrictInvoiceDeletion on Invoice_Statement__c (before delete)
  2. {
  3.     // With each of the invoice statements targeted by the trigger and that have line items, add an error to prevent them from being deleted.
  4.     for (Invoice_Statement__c invoice :[SELECT Id
  5.                                         FROM Invoice_Statement__c WHERE Id IN (SELECT Invoice_Statement__c FROM Line_Item__c) AND Id IN :Trigger.old])
  6.     {
  7.         Trigger.oldMap.get(invoice.Id).addError('Cannot delete invoice statement with line items');
  8.     }
  9. }

Line_Item__c is the Junction Object
Invoice_Statement__c  is the Master Detail Relationship


Screenshot for the Relationship




Test Data Factory

Create a Test Data factory class instead of every time creating records in test class.

  1. @isTest
  2. public class TestDataFactory
  3. {
  4.     public static Invoice_Statement__c createInvoice(boolean inv)
  5.     {
  6.         Invoice_Statement__c invoice=createInvoice();
  7.        
  8.         if(inv==true)
  9.         {
  10.             Merchandise__c me=createMerchandise();
  11.             createLineItem(invoice,me);
  12.         }
  13.        
  14.         return invoice;
  15.     }
  16.    
  17.     private static Merchandise__c createMerchandise()
  18.     {
  19.         Merchandise__c mer=new Merchandise__c(Name='Test',Description__c='test description',Price__c=1000,Total_Inventory__c=10);
  20.         insert mer;
  21.         return mer;
  22.     }
  23.    
  24.     private static Invoice_Statement__c createInvoice()
  25.     {
  26.         Invoice_Statement__c invRec=new Invoice_Statement__c(Description__c='test description');
  27.         insert invRec;
  28.         return invRec;
  29.     }
  30.    
  31.     private static Line_Item__c createLineItem(Invoice_Statement__c inv,Merchandise__c mer)
  32.     {
  33.         Line_Item__c li=new Line_Item__c(Invoice_Statement__c=inv.id,Merchandise__c=mer.Id,Unit_Price__c=mer.Price__c);
  34.         insert li;
  35.         return li;
  36.     }
  37. }

Test Class
  1. @isTest
  2. private class RestrictInvoiceDeleteTest
  3. {
  4.     static testMethod void nonDeletedData()
  5.     {
  6.         Invoice_Statement__c inv=TestDataFactory.createInvoice(true);
  7.         Test.startTest();
  8.        
  9.         Database.DeleteResult delRes=Database.Delete(inv,false);
  10.        
  11.         Test.stopTest();
  12.        
  13.         System.assert(!delRes.isSuccess());
  14.        
  15.        
  16.     }
  17.     static testMethod void deletedData()
  18.     {
  19.         Invoice_Statement__c inv=TestDataFactory.createInvoice(false);
  20.         Test.startTest();
  21.        
  22.         Database.DeleteResult delRes=Database.Delete(inv,false);
  23.        
  24.         Test.stopTest();
  25.        
  26.         System.assert(delRes.isSuccess());
  27.        
  28.     }
  29.    
  30.     static testMethod void testBulkDelete()
  31.     {
  32.         List<Invoice_Statement__c> invList=new List<Invoice_Statement__c>();
  33.         invList.add(TestDataFactory.createInvoice(true));
  34.         invList.add(TestDataFactory.createInvoice(false));
  35.        
  36.         Test.startTest();
  37.         Database.DeleteResult[] delRec=Database.Delete(invList,false);
  38.         Test.stopTest();
  39.        
  40.         System.assert(!delRec[0].isSuccess());
  41.         System.assert(!delRec[1].isSuccess());
  42.        
  43.     }
  44. }

Note: The above example provided by salesforce only. This example is very useful for beginners. If you have a doubts on this example please comment it.. I will help for you...!


Thanks for reading this post...! Hope this will helpful for you.........! 


Batch Apex and Scheduling Batch Apex in Salesforce


Batch Apex in Salesforce
To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.

Start method


          The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects to be passed to the interface method execute.

Syntax: global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}

 This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job.

Execute Method

          The execute method is called for each batch of records passed to the method. Use this method to do all required processing for each chunk of data.

Syntax: global void execute(Database.BatchableContext BC, list<P>){}

This method takes the following:
o    A reference to the Database.BatchableContext object.
o    A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, the returned list should be used.
Batches of records execute in the order they are received from the start method.

Finish Method

Syntax: global void finish(Database.BatchableContext BC){}

The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each.
The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.

Example of Batch Apex Class: 

Batch Schedule Class

  1. global class batchContactUpdate implements Database.Batchable<sObject>
  2. {
  3.     global Database.QueryLocator start(Database.BatchableContext BC)
  4.     {
  5.         String query = 'SELECT Id, FirstName,LastName FROM Contact';
  6.         return Database.getQueryLocator(query);
  7.     }
  8.  
  9.     global void execute(Database.BatchableContext BC, List<Contact> scope)
  10.     {
  11.          for(Contact a : scope)
  12.          {
  13.              a.FirstName=a.FirstName+'FirstName is Updated';
  14.              a.LastName = a.LastName +'LastName is updated';          
  15.          }
  16.          update scope;
  17.     }  
  18.     global void finish(Database.BatchableContext BC)
  19.     {
  20.     }
  21. }

Schedule Class

  1. global class BatchScheduleUpdate implements Schedulable
  2. {
  3.     global void execute(SchedulableContext sc)
  4.     {
  5.         // Implement any logic to be scheduled
  6.        
  7.         // We now call the batch class to be scheduled
  8.         BatchContactUpdate b = new BatchContactUpdate ();
  9.        
  10.         //Parameters of ExecuteBatch(context,BatchSize)
  11.         database.executebatch(b,200);
  12.     }
  13.    
  14. }

Schedule from Developer Console

  1. BatchScheduleUpdate batchSch=new BatchScheduleUpdate();
  2. String sch='0 5 2 * * ?';
  3. //System.schedule(String jobName, String cronExp, APEX_OBJECT schedulable);
  4. System.schedule('Batch Schedule', sch , batchSch);

Hope this will helpful for you...!
Thank you...!

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...