• saikrishna.G
  • NEWBIE
  • 235 Points
  • Member since 2014
  • Salesforce consultant

  • Chatter
    Feed
  • 7
    Best Answers
  • 0
    Likes Received
  • 3
    Likes Given
  • 4
    Questions
  • 31
    Replies
Hi All,

I have a schedulable class, it doesn't cover the 100% code coverage, can anyone help me.

Schedulable class
------------------------
public class DailyLeadProcessor implements Schedulable {
    public void execute(SchedulableContext sc){
        List<Lead> updaterec = new List<Lead>();
        List<Lead> leadrec = [select id,lastname,leadsource from Lead where leadsource=null limit 200];
        for(Lead le : leadrec){
            
            updaterec.add(new Lead(id = le.Id,LeadSource='Dreamforce'));
        }
        update updaterec;
    }
    
}

Test Class
--------------
@isTest
private class DailyLeadProcessorTest {
    public static string cron_exp = '0 56 11 * * ?';
    static testMethod void meth(){
        List<Lead> le = new List<Lead>();
        for(integer i=0;i<200;i++){
            Lead l = new Lead();
            l.LastName = 'sfdcuser '+i;
            l.Company = 'Fujistu';
            l.Status = 'Open - Not Contacted';
            le.add(l);
        }
        insert le;
        Test.startTest();
        List<Lead> leadlist2 = new List<Lead>();
        List<Lead> leadlist = [select id from lead where leadsource = null];
        for(Lead lead1 : leadlist){
            leadlist2.add(new Lead(id=lead1.Id,leadsource='Dreamforce'));
        }
        update leadlist2;
        
        DailyLeadProcessor dlp = new DailyLeadProcessor();
        
        
        
        String jobid = System.Schedule('leadtest',cron_exp,dlp);
        
        Test.stopTest();
        
        System.assertEquals(200, leadlist.size());
        
    }

}


Thanks in advance...
Regards,
Narasimha.
Hi,

 I need a suggestion how to remove duplicate values in the list I wrote a method which will display value from SOQL query return now there are lot of duplicate values which need to be removed and display only the unique values 

 Please suggest me how to remove the duplicate values in the list. 

Method 
/* Display product category select list */
  public List<SelectOption> ProdCatList
    {
    get
        {
           Set<String> setprocat = new Set<String>(); 
          
            ProdcatLst = [Select PricebookEntry.Product2.Category__c FROM OpportunityLineItem WHERE OpportunityId = :PageID];
            
            ProdCatList = new List<SelectOption>();
            
            for(OpportunityLineItem opl: ProdcatLst )
            {
                ProdCatList.add(new SelectOption(opl.PricebookEntry.Product2.Category__c,opl.PricebookEntry.Product2.Category__c));
                setprocat.add(opl.PricebookEntry.Product2.Category__c);
            }
            return ProdCatList ;
        }
        set;
    }
Visual force 
<apex:selectOptions value="{!ProdCatList}"></apex:selectOptions>
                 </apex:selectList>
                <apex:inputText id="prodcatdiscount" value="{!prodcatdiscount }" label="Product Discount"/>


 
Hello all, 
Question: i want to create a custom field in lead object the lable would be Activity count (Number type & API Name: Activity_count__c).
(firstly i am dealing with the task only)For a Specific lead  Whenever task created with subject ='call' the count would be increase 0 or null to 1. if the subject is other then 'Call' the Activity count field Will remain same and it will not increase after the Activity count= 1 it will increase only once. Example= When Activity count= 1 and task created the  Activity count would be remain same as before.


Ans: I have Already implement this scenario. my trigger is working ( not working when the value of Activity count=null) . StilI have issue:
Why it is not working for null value that i have Discussed before?
The code coverage is still 35% after the creating test class I want atleast 75% 

​Trigger-
 
​trigger TaskUpdateLead on task (after delete, after insert,  after update) {
    
    Set<ID> LeadIds = new Set<ID>();
    String leadPrefix = Lead.SObjectType.getDescribe().getKeyPrefix();
    if(trigger.new!=null){
        for (Task t : Trigger.new) {
            if (t.WhoId!= null && string.valueof(t.WhoId).startsWith(leadPrefix) ) {
                if(!LeadIds.contains(t.WhoId)){
                    LeadIds.add(t.WhoId);
                }
            }
        }
    }
    
    if(trigger.old!=null){
        for (Task t2 : Trigger.old) {
            if (t2.WhoId!= null && string.valueof(t2.WhoId).startsWith(leadPrefix) )
            {
                if(!LeadIds.contains(t2.WhoId)){
                    LeadIds.add(t2.WhoId);
                }
            }
        }
    }
    if (LeadIds.size() > 0){
        List<Lead> leadsWithTasks = [select id,Activity_Count__c,(select id from Tasks where  Subject = 'Call'     LIMIT 1 ) from Lead where Id IN : Leadids   ];
        List<Lead> leadsUpdatable = new List<Lead>();
        for(Lead L : leadsWithTasks){
            L.Activity_Count__c = L.Tasks.size();
            leadsUpdatable.add(L);
        }
        if(leadsUpdatable.size()>0){
            
            update leadsUpdatable;
            
        }
        
    }
}



Test Class-
 
@istest
/** Test when subject is call**/
public Class TaskupdateLead
{
    Private static testMethod void TaskinsertLead()
    {
        Task t1 = new Task();
        t1.OwnerId = UserInfo.getUserId();
        t1.Subject = 'Call';
        t1.Status = 'Not Started';
        t1.Priority = 'Normal';
        insert t1;
    }
    private static testMethod void taskwidemail()
    {
        Task t2 = new Task();
        t2.OwnerId = UserInfo.getUserId();
        t2.Subject = 'Email';
        t2.Status = 'completed';
        t2.Priority = 'Normal';
        insert t2;
    } 
}
Hope some one will help me

Thanks And Regards
Bharat Sharma
 
I am getting a constructor not defined error in Apex class when I make a List of the custom object.
Here is my code:

public with sharing class Receivable_Opp {
    public ApexPages.StandardController myRecController{get;set;}
    public  List<npe01__OppPayment__c>  Rec {get; set;}
    
    
     public ApexPages.StandardController standardOppController;
     
    
       public Receivable_Opp(ApexPages.StandardController cntrl){
           standardOppController = cntrl;
           Opportunity opp = (Opportunity)cntrl.getRecord();
          
           Rec = [Select CreatedDate, SystemModstamp, npe01__Opportunity__c, npe01__Paid__c, npe01__Scheduled_Date__c FROM npe01__OppPayment__c WHERE npe01__Paid__c = true and npe01__Opportunity__c = :opp.Id limit 1];
           myRecController = new ApexPages.StandardController(Rec);       
  }
   
}

If someone can help me resolve the issue, it would be of great help. Thanks. 
  • August 27, 2015
  • Like
  • 0
In our project there are 2 objects with parent child relationship(Lookup relationship) between ORDER and ORDER DETAILS, in ORDER object there is field called Status having picklist values(New, Processed
and Completed), here the requirment is when ever the status is changed to Processed then an ORDER DETAIL record should be created for the corresponding record in the ORDER object. Can anyone help me with code 
to implement the trigger of above scenario?
AND( 
RecordTypeId = "012E0000000NA5Q"&& 
(ISPICKVAL( Type__c, "CCM")&& 
ISNULL(Ship_Date__c))&& 

OR(NOT( 
ISPICKVAL(Outcome__c, "Left Message")), 
NOT(ISPICKVAL(Outcome__c,"Unable to Reach")), 
NOT(ISPICKVAL(Outcome__c,"Completed,Patient Started")), 
NOT(ISPICKVAL(Outcome__c,"Completed,Patient has not Started")), 
NOT(ISPICKVAL(Outcome__c,"Not ready for re-order")), 
NOT(ISPICKVAL(Outcome__c,"Patient will call Pharmacy"))))

Ship Date should only be used when Transferred to Pharmacy or Patient Scheduled Delivery are chosen outcomes  

I want a validation for ship date field whenever outcomes are only transferred to Pharmacy or patient Scheduled.It is not working can you help me.
Hi,

this is satish, Can anybody please answer the below question.Please answer if your are sure about it, please dont guess and give answer.


 UC uses a custom field on the account object to capture the account credit status. The sales team wants to display the account credit status on opportunities. Which feature should a system admin use this meet this requirement?

a. Roll Up Summary Field.
b. Workflow Field Update.
c. Lookup Field 
d. Cross Object Formula Field.

 


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Header/><soapenv:Body><p889:basicChecksDetailsResponse xmlns:p889="http://comexp.ibm.com"><basicChecksDetailsReturn>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;ExportEROData xmlns=&quot;http://w3.test.com/xmlns/ibmww/ff/sdf/ews/erodata&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://w3.test.com/xmlns/testww/ff/sdf/ews/erodata https://w3-206-beta1.w3-gslbdst.test.com/isc/esd/ibmexpws/schemas/ExportEROData_0101.xsd&quot;&gt;
    &lt;ExportChecksPassed&gt;true&lt;/ExportChecksPassed&gt;
    &lt;ExportUnderReview&gt;false&lt;/ExportUnderReview&gt;
    &lt;ExportLocations&gt;
        &lt;ExportLocationPassed&gt;US&lt;/ExportLocationPassed&gt;
    &lt;/ExportLocations&gt;
&lt;/ExportEROData&gt;
</basicChecksDetailsReturn></p889:basicChecksDetailsResponse></soapenv:Body></soapenv:Envelope>
I need "ExportChecksPassed" ,"ExportUnderReview" values 
How to parse the response 
 <?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse xmlns:ex="http://ws.apache.org/xmlrpc/namespaces/extensions"><params><param><value><array><data><value><boolean>1</boolean></value><value>OK</value></data></array></value></param></params></methodResponse>

I wanted to write logic based on Boolean value in response but am unable to parse this one 
 
Hi i have written a batch class for integration for that i have created the class in batchable class like this 
public class AccountsInsertBatch implements Database.Batchable<Account>,Database.AllowsCallouts{  
     public class accountt
         {
         public string entity_id;
         public string website_id;
         public string email;
         public string group_id;
         public string created_at;
         public string disable_auto_group_change;
         public string firstname;
         public string middlename;
         public string gender;
         public string Telephone;
         public string lastname;
         public string created_in;
         public string suffix;
         public string taxvat;
         public string ShippingAddress;  
         public string dob;      
         }
          public Iterable<Account> start(database.batchablecontext bc) {
 //Logic
     }
public void execute(database.BatchableContext BC, List<Account>accountquery){  
 //Logic
}
public void finish(Database.BatchableContext BC){ 
}
Am not getting the test coverage for the class which i have created in the Batch class.How to cover this class code covwerage?
my test class is
@isTest
public class AccountsInsertBatchTest implements HttpCalloutMock  {    
  public HTTPResponse respond(HTTPRequest req)
    { 
       HttpResponse res = new HttpResponse();
       res.setBody('{"4":{"entity_id":"4","website_id":"1","email":"ed@krishna.com","group_id":"1","created_at":"2013-09-17 14:17:12","disable_auto_group_change":"0","created_in":"Default Store View","prefix":null,"firstname":"test","middlename":null,"lastname":"Sea","suffix":"Mr.","taxvat":"123","dob":"2014-11-03 00:00:00","gender":"1"}}');
       res.setStatusCode(200);
       return res;   
    }
    @isTest static void testAccountInsert(){
        Test.StartTest();
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        MagentAccountsInsertBatch instance = new MagentAccountsInsertBatch ();
        database.executebatch(instance);        
        Test.StopTest();
        }
     @isTest static void testAccountInsert1(){
     Test.StartTest();
        insert new Account(LastName='krishna',personemail='ed@krishna.com',Entity_Id__c='1656');
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        MagentAccountsInsertBatch instance1 = new MagentAccountsInsertBatch ();
        database.executebatch(instance1); 
         Test.StopTest();    
}
}

VF Page:

<apex:page standardController="Order" extensions="O2I_OrderTest">
  <apex:form >
  <apex:sectionHeader title="New order" />
     <apex:pageBlock title=" Order Edit" mode="Edit">
     <apex:pageBlockButtons >
       <apex:commandButton action="{!save}" value="Save"/>
           <apex:commandButton action="{!cancel}" value="cancel"/>
         
            <!-- Calling controller actions by using action function when account and contacts are selected / changed  -->         
           <apex:actionFunction name="Selectcon" action="{!Selectcon}" reRender="PreparedForBlock"/>
           <apex:actionFunction name="Selectacc" action="{!Selectacc}" reRender="Addressblock"/>
         
     </apex:pageBlockButtons>
     <apex:pageBlockSection title="Information">
      <apex:inputField value="{!ord.QuoteId}"/>
       <apex:outputlabel >&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Owner</b>&nbsp;&nbsp;&nbsp;{!$User.FirstName}&nbsp;&nbsp;{!$user.Lastname}</apex:outputlabel>                  
       <apex:inputField value="{!ord.Opportunityid}"/>
       <apex:inputField value="{!ord.O2I_So_Delivery_Date__c}"/>
        <apex:inputField value="{!ord.Accountid}" required="true" onchange="Selectcon()" />
         <apex:inputField value="{!ord.Status}"/>
         <apex:inputField value="{!ord.ContractId}" required="true"/>
       <apex:inputField value="{!ord.O2I_So_Order_to_Invoices_settings__c}" required="true"/>
       <apex:inputField value="{!ord.PoNumber}"/>
       <apex:inputField value="{!ord.EffectiveDate}"/>
       <apex:inputField value="{!ord.Description}"/>                 
    </apex:pageBlockSection>
  
     <apex:pageBlockSection title="Prepared For" id="PreparedForBlock">
       <apex:inputField value="{!ord.CustomerAuthorizedByid}" onchange="Selectcon()"/>
       <apex:inputField value="{!ord.O2I_So_phone__c}"/>
        <apex:inputField value="{!ord.O2I_So_email__c}"/>
         <apex:inputField value="{!ord.O2I_Fax__c}"/>
     </apex:pageBlockSection>
   
     <apex:pageBlockSection title="Terms" columns="1">
       <apex:inputField value="{!ord.O2I_Terms_and_Conditions__c}"/>
     </apex:pageBlockSection>
   
     <apex:pageBlockSection title="Address" id="Addressblock">
       <apex:inputField value="{!ord.O2I_So_Bill_To_Name__c}"/>
                  <apex:inputField value="{!ord.O2I_Ship_To_Name__c}"/>
                  <apex:inputField value="{!ord.BillingStreet }"/>
                  <apex:inputField value="{!ord.ShippingStreet}"/>
                  <apex:inputField value="{!ord.BillingCity}"/>
                   <apex:inputField value="{!ord.ShippingCity}"/>
                   <apex:inputField value="{!ord.BillingState}"/>
                   <apex:inputField value="{!ord.ShippingState}"/>
                   <apex:inputField value="{!ord.BillingpostalCode}"/>
                   <apex:inputField value="{!ord.ShippingpostalCode}"/>
                   <apex:inputField value="{!ord.BillingCountry}"/>
                   <apex:inputField value="{!ord.ShippingCountry}"/>
     </apex:pageBlockSection>
  
   </apex:pageBlock>
  </apex:form>
</apex:page>

apex cllass:
public with sharing class O2I_OrderTest {

Public Order ord{Get;set;}
Public list<Order> ordr{Get;set;}
O2I_Order_to_Invoices_settings__c o2i;
  public list<SelectOption> ChooseCurrency{get;set;}
    public String selectedCurrency{get;set;}
    Apexpages.StandardController scon;
     Account acc;
    Contact con;

    public O2I_OrderTest(ApexPages.StandardController controller) {
     this.ord=(Order)Controller.getRecord();
      scon=controller;
       string curr;
          if(Userinfo.isMultiCurrencyOrganization() || system.test.isRunningTest()){
        if(!system.test.isRunningTest())curr=String.valueof(ord.get('CurrencyIsoCode'));
        ChooseCurrency = new List<SelectOption>();     
        chooseCurrency.add(new SelectOption(Userinfo.getDefaultCurrency(),Userinfo.getDefaultCurrency()));
        Schema.sObjectType sobject_type = Account.getSObjectType(); //grab the sobject that was passed
        Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); //describe the sobject
        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap();
        List<Schema.PicklistEntry> pick_list_values =  (!system.test.isRunningTest())? field_map.get('CurrencyISoCode').getDescribe().getPickListValues() : Account.Type.getDescribe().getPicklistValues(); //grab the list of picklist values for the passed field on the sobject
        for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
        if(a.getValue()!=Userinfo.getDefaultCurrency())
        ChooseCurrency.add(new SelectOption(a.getValue(),a.getlabel()));//add the value to our final list
            }
          
          
        }
    }

         
            Public pagereference Selectacc(){
    if(Ord.AccountId!=null){
        acc=[Select Name,BillingStreet,BillingCity,BillingState,Billingpostalcode,billingCountry,Shippingstreet,Shippingcity,shippingstate,shippingpostalcode,shippingcountry from Account where id=:Ord.AccountId];
        ord.O2I_So_Bill_To_Name__c=acc.name;
        ord.BillingStreet=acc.BillingStreet;
        ord.BillingCity=acc.BillingCity;
        ord.BillingState=acc.BillingState;
        //ord..Billingpostalcode=acc.Billingpostalcode;
        ord.billingCountry=acc.billingCountry;
        ord.O2I_Ship_To_Name__c=acc.name;
        ord.Shippingstreet=acc.Shippingstreet;
        ord.Shippingcity=acc.Shippingcity;
        ord.shippingstate=acc.shippingstate;
        ord.shippingpostalcode=acc.shippingpostalcode;
        ord.shippingcountry=acc.shippingcountry;
     
        }
        return null;
    }
                  
         
           Public pagereference Selectcon(){
    if(ord.CustomerAuthorizedByid!=null){
        con=[Select Email,Phone,Fax from Contact where id=:ord.CustomerAuthorizedByid];
        ord.O2I_So_phone__c=con.phone;
        ord.O2I_So_email__c=con.email;
        ord.O2I_Fax__c=con.fax;
        }
        return null;
    }
   
}


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Header/><soapenv:Body><p889:basicChecksDetailsResponse xmlns:p889="http://comexp.ibm.com"><basicChecksDetailsReturn>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;ExportEROData xmlns=&quot;http://w3.test.com/xmlns/ibmww/ff/sdf/ews/erodata&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://w3.test.com/xmlns/testww/ff/sdf/ews/erodata https://w3-206-beta1.w3-gslbdst.test.com/isc/esd/ibmexpws/schemas/ExportEROData_0101.xsd&quot;&gt;
    &lt;ExportChecksPassed&gt;true&lt;/ExportChecksPassed&gt;
    &lt;ExportUnderReview&gt;false&lt;/ExportUnderReview&gt;
    &lt;ExportLocations&gt;
        &lt;ExportLocationPassed&gt;US&lt;/ExportLocationPassed&gt;
    &lt;/ExportLocations&gt;
&lt;/ExportEROData&gt;
</basicChecksDetailsReturn></p889:basicChecksDetailsResponse></soapenv:Body></soapenv:Envelope>
I need "ExportChecksPassed" ,"ExportUnderReview" values 
How to parse the response 
 <?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse xmlns:ex="http://ws.apache.org/xmlrpc/namespaces/extensions"><params><param><value><array><data><value><boolean>1</boolean></value><value>OK</value></data></array></value></param></params></methodResponse>

I wanted to write logic based on Boolean value in response but am unable to parse this one 
 
Using wave analytics i want to create dashboards. Source data is from salesforce with two objects which doesn't have any dependency to draw relationship.How to create dashboard without relationship?
Hi,
I have Trigger on Order Line Item. I also wrote test class for that but it can not covers "trigger.isDelete" and  "Trigger.isUpdate" cases.
Please check following trigger and test class : 

//********************************* Trigger *************************************
trigger TotalPiecesSum on OrderItem (before update, before insert,before delete) {

list<Order> a = new list<Order>();
    set<id> OrderIDs= new set<id>();

if(trigger.isInsert || trigger.isBefore){
   for(OrderItem o : Trigger.new){
      OrderIDs.add(o.Orderid);
   }
   }

else if(trigger.isDelete){
     for(OrderItem o : Trigger.old){
         OrderIDs.add(o.Orderid);
     }
}
else 
      
     if(Trigger.isUpdate){
        for(OrderItem  o : Trigger.new){
             if(OrderItem.OrderId != null && o.Pieces__c!= trigger.oldMap.get(o.Id).Pieces__c){
                OrderIDs.add(o.OrderId);
             }      
         }
     }
    
    update a;
    
    AggregateResult[] groupedResults = [SELECT SUM(Pieces__c),OrderId FROM OrderItem where OrderId IN :OrderIDs GROUP BY OrderId ];
    system.debug('*******groupedResults **********'+groupedResults);     
    
    for(AggregateResult ar:groupedResults) {
        Id orid = (ID)ar.get('OrderId');
        system.debug('*******selected Oredr id **********'+orid);     
        Decimal count = (Decimal)ar.get('expr0');
            
        Order o1 = new Order(Id=orid);
        o1.Total_Pieces1__c= count;
        system.debug('*******Total_Pieces1__cOredr id **********'+count); 
        a.add(o1);
       }
   update a;
 
}

​//********************************* Test Class*************************************


@isTest(seeAllData = true)
private class TestTotalPiecesSum {
 
    static testMethod void myUnitTest() {
    
    //Test Account Insert

    Account a = new Account();
    a.Name = 'Test Account';
    a.Custom2__c = '000093';
    a.Business_Type__c = 'Consultant';
    insert a;

    Product2 p = new Product2();
    p.Name = ' Test Product ';
    p.Description='Test Product Entry 1';
    p.productCode = 'ABC';
    p.isActive = true;
    insert p;
    
    

    Pricebook2  standardPb = [select id, name, isActive from Pricebook2 where IsStandard = true limit 1];
    
    PricebookEntry standardPrice = new PricebookEntry();
    standardPrice.Pricebook2Id = standardPb.Id;
    standardPrice.Product2Id = p.Id;
    standardPrice.UnitPrice = 1;
    standardPrice.IsActive = true;
    standardPrice.UseStandardPrice = false;
    insert standardPrice ;
    
    //Test Order Insert
    
    Order o = new Order();
    o.Name = 'Test Order ';
    o.Status = 'Draft';
    o.EffectiveDate = system.today();
    o.EndDate = system.today() + 4;
    o.AccountId = a.id;
    o.Pricebook2Id =  standardPb.Id ;
    
    insert o;
    system.assertEquals(o.Total_Pieces1__c, null);
    
    OrderItem i = new OrderItem();
    i.OrderId = o.id;
    i.Quantity = 24;
    i.UnitPrice = 240;
    i.Pieces__c = i.Quantity;
    i.Product2id = p.id;
    i.PricebookEntryId=standardPrice.id;
    //i.Total_Price__c = i.Quantity * i.UnitPrice;
    insert i;


    Order or1 = [SELECT Total_Pieces1__c from Order where Id = :o.Id];
    system.assertEquals(or1.Total_Pieces1__c ,i.Pieces__c);


    //Test OrderItem on update

    OrderItem op1 = [select Pieces__c,PricebookEntryId from OrderItem where Id = :i.Id];
    op1.Pieces__c = 24;
    update op1;
 
    Order or2 = [SELECT Total_Pieces1__c from Order where Id = :o.Id];
    system.assertEquals(or2.Total_Pieces1__c ,op1.Pieces__c);

    //Test OrderItem on second insert
 
    OrderItem i2 = new OrderItem();
    i2.OrderId = o.id;
    i2.Quantity = 24;
    i2.UnitPrice = 240;
    i2.Pieces__c = i.Quantity;
    i2.PricebookEntryId=standardPrice.id;
    //i2.Total_Price__c = i.Quantity * i.UnitPrice;
    insert i2;
    
    AggregateResult ag1 = [select sum(Pieces__c) from OrderItem where OrderId = :o.Id];
 
    Order o3 = [select Total_Pieces1__c from Order where Id = :o.Id];
    system.assertEquals(o3.Total_Pieces1__c,ag1.get('expr0'));
 
    AggregateResult ag2 = [select sum(Pieces__c) from OrderItem where OrderId = :o.Id];
 
    Order o4 = [select Total_Pieces1__c from Order where Id = :o.Id];
    system.assertEquals(o4.Total_Pieces1__c,ag1.get('expr0'));  
 
    }  
}

It gives 66% Code Coverage.
 
how to remove the error msg of attempthow to remove the seccond error msg
Hi All,

I have a schedulable class, it doesn't cover the 100% code coverage, can anyone help me.

Schedulable class
------------------------
public class DailyLeadProcessor implements Schedulable {
    public void execute(SchedulableContext sc){
        List<Lead> updaterec = new List<Lead>();
        List<Lead> leadrec = [select id,lastname,leadsource from Lead where leadsource=null limit 200];
        for(Lead le : leadrec){
            
            updaterec.add(new Lead(id = le.Id,LeadSource='Dreamforce'));
        }
        update updaterec;
    }
    
}

Test Class
--------------
@isTest
private class DailyLeadProcessorTest {
    public static string cron_exp = '0 56 11 * * ?';
    static testMethod void meth(){
        List<Lead> le = new List<Lead>();
        for(integer i=0;i<200;i++){
            Lead l = new Lead();
            l.LastName = 'sfdcuser '+i;
            l.Company = 'Fujistu';
            l.Status = 'Open - Not Contacted';
            le.add(l);
        }
        insert le;
        Test.startTest();
        List<Lead> leadlist2 = new List<Lead>();
        List<Lead> leadlist = [select id from lead where leadsource = null];
        for(Lead lead1 : leadlist){
            leadlist2.add(new Lead(id=lead1.Id,leadsource='Dreamforce'));
        }
        update leadlist2;
        
        DailyLeadProcessor dlp = new DailyLeadProcessor();
        
        
        
        String jobid = System.Schedule('leadtest',cron_exp,dlp);
        
        Test.stopTest();
        
        System.assertEquals(200, leadlist.size());
        
    }

}


Thanks in advance...
Regards,
Narasimha.
I wrote a Custom Authentication Provider Plug-in for OAuth authentication with a SAAS service. It works fine. 

Question: How do I give error messages to the user if there is a problem during the OAuth authentication and authorization dance? Eg if the client id or secret is wrong. Or if the user declined to authorize the app when asked? 

Thanks.

PS. pages that were helpful:
http://help.salesforce.com/apex/HTViewHelpDoc?id=sso_provider_plugin_custom.htm&language=en_US#plugin_create
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/authproviderplugin.htm
Hi,

 I need a suggestion how to remove duplicate values in the list I wrote a method which will display value from SOQL query return now there are lot of duplicate values which need to be removed and display only the unique values 

 Please suggest me how to remove the duplicate values in the list. 

Method 
/* Display product category select list */
  public List<SelectOption> ProdCatList
    {
    get
        {
           Set<String> setprocat = new Set<String>(); 
          
            ProdcatLst = [Select PricebookEntry.Product2.Category__c FROM OpportunityLineItem WHERE OpportunityId = :PageID];
            
            ProdCatList = new List<SelectOption>();
            
            for(OpportunityLineItem opl: ProdcatLst )
            {
                ProdCatList.add(new SelectOption(opl.PricebookEntry.Product2.Category__c,opl.PricebookEntry.Product2.Category__c));
                setprocat.add(opl.PricebookEntry.Product2.Category__c);
            }
            return ProdCatList ;
        }
        set;
    }
Visual force 
<apex:selectOptions value="{!ProdCatList}"></apex:selectOptions>
                 </apex:selectList>
                <apex:inputText id="prodcatdiscount" value="{!prodcatdiscount }" label="Product Discount"/>


 
How can i embed three graphs on the dashboard through Visual Force Page and convert the entire 3 graphs into a PDF. Your help is highly appriciated.
,here is my code :Integer parent= getParentId(s.Forum_Year__r.Year__c ,auth.getAccessToken(),auth);
                if (!(parent>0))
                    throw new WordpressException('Parent does not exist');
                
                obj.parent=parent ;
                if (!String.isEmpty(s.Session_Type__c)) {
                    Integer etype= lookupEvent(s.Session_Type__c,auth.getAccessToken(), auth);
                    List<Integer> evlst=new List<Integer>();
                    evlst.add(etype);
                    obj.event_type=evlst;
                }
I have a situation where i will get the user locale date in APEX using 

DateTime dateTimeToFormat = DateTime.valueOf( value );
Date dateToFormat = dateTimeToFormat.date();
String formattedDatewithUSER_LOCALE = dateToFormat.format();

For example, if the localecode is en_US and timezoneid is America/Los_Angeles, then the date i would get is 9/1/2016. 

In my java code, i would get all this info along with date, locale, time zone. Along with this, i would get a date like 2016-09-01 18:42:37 as input and the requirement is to format the input date to the user date based on the locale, timezone. 

Any sugesstions..?




 
  • September 02, 2016
  • Like
  • 0
Hello all, 
Question: i want to create a custom field in lead object the lable would be Activity count (Number type & API Name: Activity_count__c).
(firstly i am dealing with the task only)For a Specific lead  Whenever task created with subject ='call' the count would be increase 0 or null to 1. if the subject is other then 'Call' the Activity count field Will remain same and it will not increase after the Activity count= 1 it will increase only once. Example= When Activity count= 1 and task created the  Activity count would be remain same as before.


Ans: I have Already implement this scenario. my trigger is working ( not working when the value of Activity count=null) . StilI have issue:
Why it is not working for null value that i have Discussed before?
The code coverage is still 35% after the creating test class I want atleast 75% 

​Trigger-
 
​trigger TaskUpdateLead on task (after delete, after insert,  after update) {
    
    Set<ID> LeadIds = new Set<ID>();
    String leadPrefix = Lead.SObjectType.getDescribe().getKeyPrefix();
    if(trigger.new!=null){
        for (Task t : Trigger.new) {
            if (t.WhoId!= null && string.valueof(t.WhoId).startsWith(leadPrefix) ) {
                if(!LeadIds.contains(t.WhoId)){
                    LeadIds.add(t.WhoId);
                }
            }
        }
    }
    
    if(trigger.old!=null){
        for (Task t2 : Trigger.old) {
            if (t2.WhoId!= null && string.valueof(t2.WhoId).startsWith(leadPrefix) )
            {
                if(!LeadIds.contains(t2.WhoId)){
                    LeadIds.add(t2.WhoId);
                }
            }
        }
    }
    if (LeadIds.size() > 0){
        List<Lead> leadsWithTasks = [select id,Activity_Count__c,(select id from Tasks where  Subject = 'Call'     LIMIT 1 ) from Lead where Id IN : Leadids   ];
        List<Lead> leadsUpdatable = new List<Lead>();
        for(Lead L : leadsWithTasks){
            L.Activity_Count__c = L.Tasks.size();
            leadsUpdatable.add(L);
        }
        if(leadsUpdatable.size()>0){
            
            update leadsUpdatable;
            
        }
        
    }
}



Test Class-
 
@istest
/** Test when subject is call**/
public Class TaskupdateLead
{
    Private static testMethod void TaskinsertLead()
    {
        Task t1 = new Task();
        t1.OwnerId = UserInfo.getUserId();
        t1.Subject = 'Call';
        t1.Status = 'Not Started';
        t1.Priority = 'Normal';
        insert t1;
    }
    private static testMethod void taskwidemail()
    {
        Task t2 = new Task();
        t2.OwnerId = UserInfo.getUserId();
        t2.Subject = 'Email';
        t2.Status = 'completed';
        t2.Priority = 'Normal';
        insert t2;
    } 
}
Hope some one will help me

Thanks And Regards
Bharat Sharma
 
I am getting a constructor not defined error in Apex class when I make a List of the custom object.
Here is my code:

public with sharing class Receivable_Opp {
    public ApexPages.StandardController myRecController{get;set;}
    public  List<npe01__OppPayment__c>  Rec {get; set;}
    
    
     public ApexPages.StandardController standardOppController;
     
    
       public Receivable_Opp(ApexPages.StandardController cntrl){
           standardOppController = cntrl;
           Opportunity opp = (Opportunity)cntrl.getRecord();
          
           Rec = [Select CreatedDate, SystemModstamp, npe01__Opportunity__c, npe01__Paid__c, npe01__Scheduled_Date__c FROM npe01__OppPayment__c WHERE npe01__Paid__c = true and npe01__Opportunity__c = :opp.Id limit 1];
           myRecController = new ApexPages.StandardController(Rec);       
  }
   
}

If someone can help me resolve the issue, it would be of great help. Thanks. 
  • August 27, 2015
  • Like
  • 0
In our project there are 2 objects with parent child relationship(Lookup relationship) between ORDER and ORDER DETAILS, in ORDER object there is field called Status having picklist values(New, Processed
and Completed), here the requirment is when ever the status is changed to Processed then an ORDER DETAIL record should be created for the corresponding record in the ORDER object. Can anyone help me with code 
to implement the trigger of above scenario?
I want to create and update user records via the salesforce API, but when i'm creating a new user in a preactive status (eq IsActive=false) salesforce sets the Active flag to true (IsActive=true). What am i missing?

All other fields are correct provisioned through my Identity Access Manager.

Thanks in advance.
AND( 
RecordTypeId = "012E0000000NA5Q"&& 
(ISPICKVAL( Type__c, "CCM")&& 
ISNULL(Ship_Date__c))&& 

OR(NOT( 
ISPICKVAL(Outcome__c, "Left Message")), 
NOT(ISPICKVAL(Outcome__c,"Unable to Reach")), 
NOT(ISPICKVAL(Outcome__c,"Completed,Patient Started")), 
NOT(ISPICKVAL(Outcome__c,"Completed,Patient has not Started")), 
NOT(ISPICKVAL(Outcome__c,"Not ready for re-order")), 
NOT(ISPICKVAL(Outcome__c,"Patient will call Pharmacy"))))

Ship Date should only be used when Transferred to Pharmacy or Patient Scheduled Delivery are chosen outcomes  

I want a validation for ship date field whenever outcomes are only transferred to Pharmacy or patient Scheduled.It is not working can you help me.
Hello everyon
I have created one Rest api for creating Contacts. How I can test my rest api by passing xml . is ther any way that I test my rest api. I tested using json parser in workbench but I am not able to test my rest api apex code by parsing xml.

//apex class    
@Httppost
    Global static String candidateInformation(List<Candidate> Candidates, String reqSessionId) {

Note: How I can read the xml in Rest api apex class ?
 
//Parsing xml request
<?xml version="1.0" encoding="UTF-8"?>
-<Candidates>
   -<Candidate>
            <JobID>string</JobID>
             <EmailAddress>string</EmailAddress>
              <FirstName>string</FirstName>
              <LastName>string</LastName>
              <Phone>string or int</Phone>        
             -<CoverLetter>
                   -<![CDATA[string]]>
              </CoverLetter>
              -<ResumeText>
                    -<![CDATA[string]]>
              </ResumeText>
             -<Base64Stream>
                   -<![CDATA[string]]>
               </Base64Stream>
     </Candidate>
</Candidates>
Hi folks,
I need a help from you, in my project there is a need to send csv files from salesforce to third  party client(java technology). For this we are using REST PUT service, and to connect and to send csv files from salesforce I coded as specifed below, I am getting the following error which is taken from my debug log file
DEBUG|System.HttpResponse[Status=Unsupported Media Type, StatusCode=415]

and the code is
     RESTInfo__c ri = RESTInfo__c.getInstance('cart');
            HttpRequest req = new HttpRequest();
            string url = ri.endpoint__c; // I mentioned endpoint url in custom settings
            req.setMethod('PUT');
            req.setEndpoint(url);
           // req.setHeader('Content-Type', ri.content_type__c ); //req.setHeader('content-type', 'application/csv');
            req.setHeader('email', ri.email__c);  //I mentioned endpoint email & password in custom settings
            req.setHeader('password', ri.password__c);  
            req.setHeader('carttype', ri.carttype__c);  
            req.setHeader('accountId', accMap.get(i).Account_ID__c); 
            req.setHeader('Content-Type', 'application/json');
            //req.setHeader('input', 'cart,cartcsv');
            req.setBody(cartCsv); 
            Http http = new Http();
            try {
                
                HTTPResponse res = http.send(req);
                System.debug('The response::::'+res);
                System.debug(res.toString());
                System.debug('STATUS:'+res.getStatus());
                System.debug('STATUS_CODE:'+res.getStatusCode());
                if(res.getStatus() != '200'){
                    isError = true;
                }
                
            }catch(System.CalloutException e) {
                system.debug('The exception :::'+e);
                isError = true;
                system.debug('Making error flag as true ::isError-'+isError);

Thanks in Advance
trigger expenses on Expense_Payouts__c (after insert,after update) 
{

list<string> departmentnames= new list<string>();
Decimal amount;
for(Expense_Payouts__c ep:trigger.new)
{

departmentnames.add(ep.department__c);

amount=ep.Amount__c;
               
}


list<Employee__c> employee = [select id,name,Expense__c,Company_Expenses__c,Department_Cost_Center__c from
				 Employee__c where Department_Cost_Center__c IN:departmentnames];
system.debug('employeeeee.......'+employee);

decimal divAmount;
if(employee.size()!=null)
{
divAmount=amount/employee.size();
}

system.debug('test.......'+divAmount);
system.debug('test222222.......'+amount);

for(Employee__c e:employee )
{
if(e.Department_Cost_Center__c !='Others' && divAmount!=null)
{
e.Expense__c=((e.expense__C==null)?0:e.expense__C)+divAmount;
}

}
update employee;

}

//////////////////trigger 2///////////////////////////

trigger otherdepartment on Expense_Payouts__c (after insert, after update) {

list<employee__c> employ= [select id,name,Expense__c,Company_Expenses__c,Department_Cost_Center__c from Employee__c];
decimal amount;

for(Expense_Payouts__c e:trigger.new)
{
if(e.department__c=='Others')
{
amount=e.Amount__c;
}

}
Decimal diamount;
if(employ.size()!=null && amount!=null)
{
diamount=amount/employ.size();
}

for(employee__c e:employ)
{
if(diamount!=null){
e.Company_Expenses__c=((e.Company_Expenses__c==null)?0:e.Company_Expenses__c)+diamount;
}
}
update employ;

}
I Wrote two triggers on a same object..Now i am trying to merge them but cant able to merge both functionality in one trigger..
Please help by ur thoughts...
Thanks..........
hi,

        I want to update the picklist option dynamically  in picklist field while i selecting the  picklist option in another picklist field ,for example 

  1.state(picklist field)--india,america,if i chose the picklist option as america and clicks any button,it (america)will update in another pickist field.and also have to open the two text fields also.

thanks,