• Amit Chaudhary 8
  • ALL STAR
  • 42019 Points
  • Member since 2014
  • Salesforce CRM Consultant


  • Chatter
    Feed
  • 1226
    Best Answers
  • 1
    Likes Received
  • 32
    Likes Given
  • 3
    Questions
  • 5932
    Replies
I've written this scheduable apex class but I can't figure out how to write a test class. 
global class UpdateCSMTeam implements Schedulable {
    
    global void execute(SchedulableContext ctx) {

    // Create a list of the accounts to update
    List<Account> myList = new List<Account>();

    // Create a list of all the customer accounts
    List<Account> accountList = [SELECT Id, Account_Manager__c FROM Account WHERE Type = 'Customer'];

    for (Account acc : accountList){
    	// one
    	if(acc.Account_Manager__c == '0051I0000027OCuQAM') {
    		acc.Onboarding_Specialist__c = '0051I0000029k0yQAA';
    		acc.Product_Specialist__c = '0051I0000027ODJQA2';

    		myList.add(acc);
    	}
    	// two
    	if(acc.Account_Manager__c == '0051I0000029k3sQAA') {
    		acc.Onboarding_Specialist__c = '0051I0000029k0ZQAQ';
    		acc.Product_Specialist__c = '0051I000002Q8XaQAK';

    		myList.add(acc);
    	}
    	// three
    	if(acc.Account_Manager__c == '0051I000002baVoQAI') {
    		acc.Onboarding_Specialist__c = '0051I000002slVdQAI';
    		acc.Product_Specialist__c = '0051I000002QShlQAG';

    		myList.add(acc);
    	}
    	// four
    	if(acc.Account_Manager__c == '0051I000002s0dpQAA') {
    		acc.Onboarding_Specialist__c = '0051I000002QPrUQAW';
    		acc.Product_Specialist__c = '0051I0000027ODOQA2';

    		myList.add(acc);
    	}
    	// five
    	if(acc.Account_Manager__c == '0051I000002QPrTQAW') {
    		acc.Onboarding_Specialist__c = '0051I000002s0dqQAA';
    		acc.Product_Specialist__c = '0051I000002stE6QAI';

    		myList.add(acc);
    	}
    }

    update myList;

    }
}
Any help appreciated!
Hello, I am new to APEX, Can someone tell me if this is possible to have duplicate Key in a MAP. I am adding element from a list to a map and when i print my map, i see duplicate value of the key. Here is how my map and its data items are defined.

public class ZTECase
    {
        public string OracleCaseNumber{get;set;}
    }
public class ZTEContact
    {
        public string FirstName{get;set;}
        public string LastName{get;set;}
        public string EmailAddress{get;set;}  
}

  map<ZTECase,ZTEContact> mapZTEData=new map<ZTECase,ZTEContact>
                      ZTECase objZTECase=new ZTECase();    
                      ZTEContact objZTEContact=new ZTEContact();    

In this map, we are adding  OracleCaseNumber and Contact info from Oracle Service Cloud. When i am printing this map post my addition, i see duplicate OracleCaseNumber which is my Key in the map ZTECase. Please suggest
 
Hi and thanks in Advance.  I was able to write a test code for my class, but need help.  This provides 5% coverage.

Class:
global with sharing class TMWSendOrderService 
{
    public class OrderResponse 
    {
        string OrderNumber;
        List<string> Comments = new List<string>();
        List<string> Errors = new List<string>();
        string CaseNumber;
    }
  
  public class FuelOrdered 
    {
    string Type;
    integer Amount;
  }
    
    public class TmwOrder 
    {
        string CaseNumber;
        Date DeliveryDate;
        string DeliveryTimeframe;
        string CompanyCode;
        string Origin;
    List<FuelOrdered> FuelList = new List<FuelOrdered>();
    List<string> ErrorsFound = new List<string>();
    }
  
    webservice static String SendToTmw(string cid) 
    {
    system.debug('cid: ' + cid);
        return SendOrderToTmw(cid);
    }
  
    private static string SendOrderToTmw(string cid)
    {

        if(String.isBlank(cid))
            return 'INVALID_PARAMETERS';
        
        // get list of cases that have not yet been sent to TMW and have a valid quantity
    List<Case> sfCases = [ SELECT Id, AccountId, CaseNumber, Origin, 
        RQ_Delivery_Date__c, RQ_Delivery_Timeframe__c, 
        Fuel1_Requested_Type__c, Fuel1_Requested_Amount__c, 
        Fuel2_Requested_Type__c, Fuel2_Requested_Amount__c, 
        Fuel3_Requested_Type__c, Fuel3_Requested_Amount__c, 
        Fuel4_Requested_Type__c, Fuel4_Requested_Amount__c
      FROM Case WHERE id = :cid 
      AND TMW_Order_Num__c = '' //AND SendtoTMW__c = false 
      AND ( 
        Fuel1_Requested_Amount__c > 0 OR Fuel2_Requested_Amount__c > 0 
                OR Fuel3_Requested_Amount__c > 0 OR Fuel4_Requested_Amount__c > 0 
            ) ]; 
        // Instantiate a new http object.  Create a list of cases and send to REST service
        if(sfCases.size() == 0)
            return 'This case requires: valid quantity, requested delivery time and timeframe, and cannot be a resubmission.';
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        Case sfCase = sfCases[0];
    // get company  code from translation table
    string companyCode = 
        [  
          SELECT Surrogate_ID__c FROM Translation_Table__c 
          WHERE IntegratedSite__c = :sfCase.AccountId LIMIT 1
        ].Surrogate_ID__c.replace('TMW-','');
        // populate case
        TmwOrder tmwOrder = new TmwOrder();
        tmwOrder.CaseNumber = sfCase.casenumber;
        tmwOrder.DeliveryDate = sfCase.RQ_Delivery_Date__c;
        tmwOrder.DeliveryTimeframe = sfCase.RQ_Delivery_Timeframe__c;
        tmwOrder.CompanyCode = companyCode;
        tmwOrder.Origin = sfCase.Origin;
        FuelOrdered item = new FuelOrdered();
        // create FuelOrdered list from requested types/amounts
        item.Type = sfCase.Fuel1_Requested_Type__c;
        item.Amount = Integer.valueOf(sfCase.Fuel1_Requested_Amount__c);
        if (item.Amount > 0) tmwOrder.FuelList.Add(item);
        item = new FuelOrdered();
        item.Type = sfCase.Fuel2_Requested_Type__c;
        item.Amount = Integer.valueOf(sfCase.Fuel2_Requested_Amount__c);
        if (item.Amount > 0) tmwOrder.FuelList.Add(item);
        item = new FuelOrdered();
        item.Type = sfCase.Fuel3_Requested_Type__c;
        item.Amount = Integer.valueOf(sfCase.Fuel3_Requested_Amount__c);
        if (item.Amount > 0) tmwOrder.FuelList.Add(item);
        item = new FuelOrdered();
        item.Type = sfCase.Fuel4_Requested_Type__c;
        item.Amount = Integer.valueOf(sfCase.Fuel4_Requested_Amount__c);
        if (item.Amount > 0) tmwOrder.FuelList.Add(item);
        string postString = JSON.serialize(tmwOrder);
        req.setBody(postString);
        req.setEndpoint('http://dev-tmw.sunocolp.com/api/CreateTMWOrder');
        req.setHeader('content-type','application/json');
        req.setTimeout(60000);
        req.setMethod('POST');
        //req.setCompressed(true);
        // Send the request, and return a response
        HttpResponse res = h.send(req);
        string bod = res.getBody();
        system.debug(bod);
        OrderResponse rsp = (OrderResponse)JSON.deserialize(bod, OrderResponse.class);
        system.debug('order response: ' + rsp);
        Case newCase;
        if (rsp.OrderNumber != null && rsp.OrderNumber !='')
        {
            // If Order was created, add order # to the case
            newCase = 
      [  
        Select Id, TMW_Order_Num__c, SFtoTMWSent__c, SendtoTMW__c  
                FROM Case 
                WHERE CaseNumber = :rsp.CaseNumber
            ];
            newCase.TMW_Order_Num__c = rsp.OrderNumber;
            newCase.SendtoTMW__c = true;
            newCase.SFtoTMWSent__c = date.today();
            update newCase;
        }
        else
        {
            // No order # was returned.  Mark case as sent to TMW.
            newCase = 
            [  
                 SELECT Id, SFtoTMWSent__c, SendtoTMW__c  
                 FROM Case 
                 WHERE CaseNumber = :rsp.CaseNumber
            ];
            newCase.SendtoTMW__c = true;
            newCase.SFtoTMWSent__c = date.today();
            update newCase;
        }
        // add case comments (if any)
        for (Integer i = 0; i < rsp.Comments.size(); i++)
        {
            CaseComment com = new CaseComment();
            com.ParentId = newCase.id;
            com.CommentBody = rsp.Comments[i];
            insert com;
        }        
        return 'Order submitted successfully!';
    }
}
---------------------------
Test Class:
@isTest
 
private class TMWSendOrderService_Test{
 
  @testSetup
 
  static void setupTestData(){
 
    test.startTest();
 
    Translation_Table__c translation_table_Obj = new Translation_Table__c(Integration_Status__c = false);
 
    Insert translation_table_Obj; 
 
    test.stopTest();
 
  }
 
   static testMethod void test_TmwOrder(){
 
    List<Translation_Table__c> translation_table_Obj  =  [SELECT Integration_Status__c, Name from Translation_Table__c];
 
    System.assertEquals(true,translation_table_Obj.size()>0);
 
    TMWSendOrderService obj01 = new TMWSendOrderService();
 
    TMWSendOrderService.OrderResponse obj11 = new TMWSendOrderService.OrderResponse();
 
    TMWSendOrderService.FuelOrdered obj21 = new TMWSendOrderService.FuelOrdered();
 
    TMWSendOrderService.TmwOrder obj31 = new TMWSendOrderService.TmwOrder();
 
  }
 
}

 
I am getting the annoying "Attempt to de-reference a null obect" error when trying to deploy a VF page and Class/Test Class. I have 100% code coverage on my test class and it functions perfectly in sandbox. I cannot seem to figure out where/why I am getting the error. Below is the code for both the class and test class. I am getting an error at line 64, 96, and 127 in the class. 
public class ctrl_qliEstimatedSellFor {
    
    public list< QuoteLineItems__c > qli_List	{get;set;}
    public List < SystemsOrOptions__c > soo_List {get;set;}
    private final Quotes__c qte_sObj;
    decimal pem {get;set;}
    decimal pf {get;set;}
    decimal se {get;set;}
    decimal GMNC {get;set;}
    decimal CostTotal {get;set;}
    decimal TravelCost {get;set;}
    decimal TravelCostTest {get;set;}
    decimal CommissionPercentage {get;set;}
    decimal SellForWoCommission {get;set;}
    decimal CommissionAmount {get;set;}
    decimal EstimatedSellForTotal {get;set;}
    
    public ctrl_qliEstimatedSellFor( ApexPages.StandardController stdController ){
        
        this.qte_sObj = ( Quotes__c )stdController.getRecord();
        
        qli_List = new list< QuoteLineItems__c >();
        soo_List = new List <SystemsOrOptions__c > ();
        TravelCost = 0;
        TravelCostTest = 0;
        EstimatedSellForTotal = 0;
        
        for( QuoteLineItems__c q : [SELECT Id,Name, RelatedQuote__r.CommissionPercentageForCalculations__c, RelatedQuote__r.FinalCommissionAmount__c, Qty__c, FlowItemNumber__c, RelatedQuote__r.SellForPricewoCommission__c, RelatedQuote__c, 
                                    Description2__c, ContributionCode__c, TotalCost__c, TaxCost__c, CustomerFacingPrice__c, SellForEstimated__c, RelatedQuote__r.GMNC__c, RelatedQuote__r.Name, SystemsOrOptions__r.CostOfTravel__c, 
                                    PercentageOfCost__c, RelatedQuote__r.BaseOptionsEquipmentTotalCost__c, AdHocCost__c, AdHocSegments__c, Type__c, ProductType__c, SystemsOrOptions__r.MechanicalInstallationCost__c, 
                                    SystemsOrOptions__r.ElectricalInstallationCost__c, SystemsOrOptions__r.StartupServicesCost__c, AdhocTotalCost__c
                                    FROM QuoteLineItems__c
                                    WHERE RelatedQuote__c = : qte_sObj.Id
                                    ORDER By Name ASC] ){
                                        qli_List.add( q );
                                    }
        
        for (SystemsOrOptions__c s : [SELECT Id, Name, CostOfTravel__c FROM SystemsOrOptions__c
                                      WHERE Quote__c = : qte_sObj.Id]){
                                          soo_List.add(s);
                                          IF(s.CostofTravel__c != null){
                                              TravelCostTest = (TravelCostTest + s.CostOfTravel__c);
                                              system.debug('TravelCostTest************************' + TravelCostTest);
                                          }
                                          else{
                                              system.debug('Null Value in s.CostOfTravel ' + s.Id);
                                          }
                                      }
        Integer counter = [SELECT count() FROM QuoteLineItems__c WHERE RelatedQuote__c = : qte_sObj.Id];
        
        for( QuoteLineItems__c qli : qli_List ){
            if( qli.ContributionCode__c == '500M1' && qli.TotalCost__c != null){
                TravelCost = 0;
                gmnc = qli.RelatedQuote__r.GMNC__c;
                pem = 0.065 * (qli.TotalCost__c+ (0.047* qli.TotalCost__c));
                pf = 0.047 * qli.TotalCost__c;
                se = 0.132 * qli.TotalCost__c;
                qli.TaxCost__c = pem + pf + se;
                CommissionPercentage = qli.RelatedQuote__r.FinalCommissionAmount__c / qli.RelatedQuote__r.SellForPricewoCommission__c;
                
                //Quotes Gross Margin Net of Commission
                GMNC = qli.RelatedQuote__r.GMNC__c/100;
                CostTotal = qli.TotalCost__c + qli.TaxCost__c;
                TravelCost = (TravelCostTest * (qli.PercentageofCost__c/100));
                SellForWoCommission = ((CostTotal + TravelCost) / (1-GMNC));
                CommissionAmount = ((SellForWoCommission * CommissionPercentage) / (1-GMNC));
                qli.SellForEstimated__c = SellForWoCommission + CommissionAmount;
                EstimatedSellForTotal = qli.SellForEstimated__c + EstimatedSellForTotal;
                
                system.debug('GMNC ' + GMNC);
                system.debug('PEM ' + pem);
                system.debug('SE ' + Se);
                system.debug('PF ' + Pf);
                system.debug('Cost Total ' + CostTotal);
                system.debug('TravelCost '+ TravelCost);
                system.debug('Estimated Sell For w/o Commission ' + SellForWoCommission);
                system.debug('Commission Amount ' + (SellForWoCommission * CommissionPercentage));
                system.debug('Estimated Sell For ' + EstimatedSellForTotal);
                system.debug('QLI Percentage of Cost +' + qli.PercentageofCost__c);
                system.debug('Travel Cost Test ' + TravelCostTest);
            }
        }
        for( QuoteLineItems__c qli : qli_List ){
            if(qli.ContributionCode__c == 'OEM1' && qli.TotalCost__c != null){
                travelCost = 0;
                gmnc = qli.RelatedQuote__r.GMNC__c;
                pf = 0.047 * qli.TotalCost__c/2;
                pem = 0.065 * (qli.TotalCost__c + pf);
                se = 0.132 * qli.TotalCost__c;
                qli.TaxCost__c = (pem + pf + se);
                CommissionPercentage = qli.RelatedQuote__r.FinalCommissionAmount__c / qli.RelatedQuote__r.SellForPricewoCommission__c;
                system.debug('Commission Percentage' + CommissionPercentage);
                
                GMNC = qli.RelatedQuote__r.GMNC__c/100;
                CostTotal = qli.TotalCost__c + qli.TaxCost__c;
                TravelCost = (TravelCostTest * (qli.PercentageofCost__c/100));
                SellForWoCommission = ((CostTotal + TravelCost) / (1-GMNC));
                CommissionAmount = ((SellForWoCommission * CommissionPercentage) / (1-GMNC));
                qli.SellForEstimated__c = SellForWoCommission + CommissionAmount;
                EstimatedSellForTotal = qli.SellForEstimated__c + EstimatedSellForTotal;
                
                system.debug('GMNC ' + GMNC);
                system.debug('PEM ' + pem);
                system.debug('SE ' + Se);
                system.debug('PF ' + Pf);
                system.debug('Cost Total ' + CostTotal);
                system.debug('TravelCost '+ TravelCost);
                system.debug('Estimated Sell For w/o Commission ' + SellForWoCommission);
                system.debug('Commission Amount ' + (SellForWoCommission * CommissionPercentage));
                system.debug('Estimated Sell For ' + EstimatedSellForTotal);
                system.debug('QLI Percentage of Cost +' + qli.PercentageofCost__c);
                system.debug('Travel Cost Test ' + TravelCostTest);
            } 
        }
        for( QuoteLineItems__c qli : qli_List ){
            if(qli.ContributionCode__c == 'CTM1' && qli.TotalCost__c != null){
                TravelCost = 0;
                gmnc = qli.RelatedQuote__r.GMNC__c;
                pf = 0.047 * qli.TotalCost__c/2;
                pem = 0.065 * (pf);
                qli.TaxCost__c = pem + pf;
                CommissionPercentage = qli.RelatedQuote__r.FinalCommissionAmount__c / qli.RelatedQuote__r.SellForPricewoCommission__c;
                
                //Quotes Gross Margin Net of Commission
                GMNC = qli.RelatedQuote__r.GMNC__c/100;
                CostTotal = qli.TotalCost__c + qli.TaxCost__c;
                TravelCost = (TravelCostTest * (qli.PercentageofCost__c/100));
                SellForWoCommission = ((CostTotal + TravelCost) / (1-GMNC));
                CommissionAmount = ((SellForWoCommission * CommissionPercentage) / (1-GMNC));
                qli.SellForEstimated__c = SellForWoCommission + CommissionAmount;
                EstimatedSellForTotal = qli.SellForEstimated__c + EstimatedSellForTotal; 
                
                system.debug('GMNC ' + GMNC);
                system.debug('PEM ' + pem);
                system.debug('SE ' + Se);
                system.debug('PF ' + Pf);
                system.debug('Cost Total ' + CostTotal);
                system.debug('TravelCost '+ TravelCost);
                system.debug('Estimated Sell For w/o Commission ' + SellForWoCommission);
                system.debug('Commission Amount ' + (SellForWoCommission * CommissionPercentage));
                system.debug('Estimated Sell For ' + EstimatedSellForTotal);
                system.debug('QLI Percentage of Cost +' + qli.PercentageofCost__c);
                system.debug('Travel Cost Test ' + TravelCostTest);
            }
        }
    }
}
 
@IsTest
public class ctrl_qliEstimatedSellFor_test {
    static testMethod void Test1(){
        RFQ__c rfqObj                              = new RFQ__c();
        insert rfqObj;
        
        Account a = new Account();
        a.Name = 'Name';
        insert a;
        
        Opportunity opp = new Opportunity();
        opp.StageName = 'Developing Proposal';
        opp.Name = 'test';
        opp.CloseDate = system.today();
        insert opp;
        
        Quotes__c q = new Quotes__c();
        q.RFQ__c = rfqObj.Id;
        q.Name = 'test';
        q.Opportunity__c = opp.Id;
        q.QuoteType__c = 'Budgetary';
        q.MarginPercentage__c = 0.32;
        q.SetSellForPrice__c = 2000000;
        q.CommissionCalculationType__c = 'Shick Standard';
        q.FinalCommissionAmountPB__c = 0;
        insert q;
        
        SystemsOrOptions__c soo = new SystemsOrOptions__c();
        soo.Quote__c = q.Id;
        soo.Locked__c = false;
        soo.Name		= 'Test';
        soo.MechanicalInstallationCost__c = 0;
        soo.ElectricalInstallationCost__c = 0;
        soo.StartUpServicesCost__c = 0;
        insert soo;
        
        QuoteLineItems__c qli = new QuoteLineItems__c();
        qli.RelatedQuote__c = q.Id;
        qli.SystemsOrOptions__c = soo.Id;
        qli.ClonedItem__c = false;
        qli.AdHocCost__c = 4000;
        qli.Qty__c = 100;
        qli.AdHocSegments__c = 'System Custom';
        qli.Type__c = 'Custom';
        qli.ProductType__c = 'Ad-Hoc';
        
        
        insert qli;
               
        system.test.startTest();
        ApexPages.StandardController sc = new ApexPages.StandardController( q );
        ctrl_qliEstimatedSellFor ctrl = new ctrl_qliEstimatedSellFor( sc );
        
        system.test.stopTest();

    }
    
    static testMethod void Test2(){
        RFQ__c rfqObj                              = new RFQ__c();
        insert rfqObj;
        
        Account a = new Account();
        a.Name = 'Name';
        insert a;
        
        Opportunity opp = new Opportunity();
        opp.StageName = 'Developing Proposal';
        opp.Name = 'test';
        opp.CloseDate = system.today();
        insert opp;
        
        Quotes__c q = new Quotes__c();
        q.RFQ__c = rfqObj.Id;
        q.Name = 'test';
        q.Opportunity__c = opp.Id;
        q.QuoteType__c = 'Budgetary';
        q.MarginPercentage__c = 0.32;
        q.SetSellForPrice__c = 2000000;
        q.CommissionCalculationType__c = 'Shick Standard';
        q.FinalCommissionAmountPB__c = 0;
        insert q;
        
        SystemsOrOptions__c soo = new SystemsOrOptions__c();
        soo.Quote__c = q.Id;
        soo.Locked__c = false;
        soo.Name		= 'Test';
        soo.MechanicalInstallationCost__c = 0;
        soo.ElectricalInstallationCost__c = 0;
        soo.StartUpServicesCost__c = 0;
        insert soo;
        
        QuoteLineItems__c qli = new QuoteLineItems__c();
        qli.RelatedQuote__c = q.Id;
        qli.SystemsOrOptions__c = soo.Id;
        qli.ClonedItem__c = false;
        qli.AdHocCost__c = 4000;
        qli.Qty__c = 100;
        qli.AdHocSegments__c = 'OEM';
        qli.Type__c = 'Custom';
        qli.ProductType__c = 'Ad-Hoc';
        
        insert qli;
               
        system.test.startTest();
        ApexPages.StandardController sc = new ApexPages.StandardController( q );
        ctrl_qliEstimatedSellFor ctrl = new ctrl_qliEstimatedSellFor( sc );
        
        system.test.stopTest();

    }
    
        static testMethod void Test3(){
        RFQ__c rfqObj                              = new RFQ__c();
        insert rfqObj;
        
        Account a = new Account();
        a.Name = 'Name';
        insert a;
        
        Opportunity opp = new Opportunity();
        opp.StageName = 'Developing Proposal';
        opp.Name = 'test';
        opp.CloseDate = system.today();
        insert opp;
        
        Quotes__c q = new Quotes__c();
        q.RFQ__c = rfqObj.Id;
        q.Name = 'test';
        q.Opportunity__c = opp.Id;
        q.QuoteType__c = 'Budgetary';
        q.MarginPercentage__c = 0.32;
        q.SetSellForPrice__c = 2000000;
        q.CommissionCalculationType__c = 'Shick Standard';
        q.FinalCommissionAmountPB__c = 0;
        insert q;
        
        SystemsOrOptions__c soo = new SystemsOrOptions__c();
        soo.Quote__c = q.Id;
        soo.Locked__c = false;
        soo.Name		= 'Test';
        soo.MechanicalInstallationCost__c = 0;
        soo.ElectricalInstallationCost__c = 0;
        soo.StartUpServicesCost__c = 0;
        insert soo;
        
        QuoteLineItems__c qli = new QuoteLineItems__c();
        qli.RelatedQuote__c = q.Id;
        qli.SystemsOrOptions__c = soo.Id;
        qli.ClonedItem__c = false;
        qli.AdHocCost__c = 4000;
        qli.Qty__c = 100;
        qli.AdHocSegments__c = 'Controls';
        qli.Type__c = 'Controls';
        qli.ProductType__c = 'Ad-Hoc';
        
        insert qli;
               
        system.test.startTest();
        ApexPages.StandardController sc = new ApexPages.StandardController( q );
        ctrl_qliEstimatedSellFor ctrl = new ctrl_qliEstimatedSellFor( sc );
        
        system.test.stopTest();

    }
}

How can I test this for 100% coverage?
@HttpGet
global static List<Box__c> getBox(){
    RestRequest req = RestContext.request;
    String boxId = req.params.get('Id');
    if(boxId == null)
    {
        return [SELECT Id, Title__c
                FROM Box__c
                LIMIT 1000];
    }
    else
    {
        List<Box__c> boxList;
        boxList = [SELECT Id, Title__c 
                   FROM Box__c
                   WHERE Id =: boxId
                   LIMIT 1000];
        return boxList;
    }
}
My test It works, but only 80%:
@isTest
static void testBox() {
    Id recordId = idd();
    RestRequest request = new RestRequest();
    request.requestUri = System.URL.getSalesforceBaseUrl().toExternalForm() + '/services/apexrest/Box__c/' + recordId;            
    request.httpMethod = 'GET';
    RestContext.request = request;

    List<Box__c> b = OurClass.getBox();

    for(Box__c pneBox : b){
        System.assertEquals(pneBox.Id, recordId);
    }
}

static Id idd() {
    Box__c bb = new Box__c(
        Title__c = 'Title',
    );
    insert bb;
    return bb.Id;
}
Hello,
I'm trying to pass the account Id to the new Contact role but I'm getting this error: Compile Error: Variable does not exist: currentAccoun​t.Id
public class AccountWithContactRolesExtension{	
	Account currentAccount {get; set;}
	
	public AccountWithContactRolesExtension(ApexPages.StandardController stdCtrl){
		std=stdCtrl;
		lstInner = new List<innerClass>();
		addMore();
		selectedRowIndex = '0';
		currentAccount = (Account) std.getRecord();
		System.Debug('#######current Account Id:' + currentAccount.Id); 
	}

    public void Add()
    {   
        count = count+1;
       // AccountId = getAccount().id;
        addMore();      
    }
    
    /*Begin addMore*/
    public void addMore()
    {
        //call to the iner class constructor
        innerClass objInnerClass = new innerClass(count);
        
        //add the record to the inner class list
        lstInner.add(objInnerClass);    
        system.debug('lstInner---->'+lstInner);            
    }/* end addMore*/
        
    public class innerClass {     

        public String recCount
        {get;set;}
		
        /*Inner Class Constructor*/
        public innerClass(Integer intCount) {
            recCount = String.valueOf(intCount);        
            
            /*create a new AccountContactRole*/
            if(intCount>0 && contactRole == null && currentRecord != null){
               AccountContactRole   contactRole = new AccountContactRole(AccountId=currentAccount.Id);
            }    
        }/*End Inner class Constructor*/    
    }/*End inner Class*/
}
Thank you for your help.
 
Here's my code, page, extension & test.  No coverage for the entire list of attachments.
Extension:
public class CaseListController {
    
    private final Case cas; 
    private String sortOrder = 'CreatedDate'; 
    public Case cCas;
    public Case pCas; 
    public Id theParent;
    
    public CaseListController(ApexPages.StandardController stdController) {
        this.cas = (Case)stdController.getRecord();
        cCas=[SELECT id, parentid, casenumber FROM case WHERE id=:cas.id];
        pCas=[SELECT id FROM case WHERE id=:cCas.ParentId]; 
        theParent=pCas.id;
        System.debug('The Parent Record is: ' + theParent); 
    }
    
    public List<Attachment> getAttachments() {
        List<Attachment> results; 
        If(theParent != null){
            results = Database.query(
                'SELECT Id, parentid, parent.name, name, CreatedDate, ContentType, ownerid ' + 
                'FROM Attachment ' + 
                ' WHERE parentid =:theParent ' + 
                'ORDER BY ' + sortOrder + ' DESC ' + 
                'LIMIT 10'
            ); 
        } 
        return results;
    }
}
Page: 
<apex:page standardcontroller="Case" extensions="CaseListController" sidebar="false" showHeader="false" >
    <apex:form >
        <apex:pageBlock title="Parent Attachments" id="attachments_list"> 
            <apex:pageBlockTable value="{! attachments }" var="at">
                <apex:column headervalue="File">
                    <apex:outputLink value="/servlet/servlet.FileDownload?file={! at.id}" target="_blank">{! at.Name}
                    </apex:outputLink>
                </apex:column>
                <apex:column value="{! at.contenttype }"/>
                <apex:column value="{! at.createddate }"/>
                <apex:column value="{! at.ownerid }"/>
                <apex:column value="{! at.parent.name }" headerValue="Case"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Test:  
@isTest
public class CaseListController_Test {

    public static testMethod void testMyController() {
        Account testAccount = new Account();
		testAccount.Name='Test Account'; 
        testAccount.Phone='(999) 999-9999';
        
        Case ParentCase = new Case();
        ParentCase.AccountId = testAccount.id; 
        ParentCase.RecordTypeId='012L000000073y2';
        ParentCase.Reason__c='Move User';
        ParentCase.Subject = 'Test Parent Case'; 
        ParentCase.Description = 'Test Parent Case'; 
        insert ParentCase; 
        
        Case ChildCase = new Case();
        ChildCase.AccountId = testAccount.id; 
        ChildCase.ParentId = ParentCase.id;
        ChildCase.RecordTypeId='012L000000073y2';
        ChildCase.Reason__c='Move User';
        ChildCase.Subject = 'Test Parent Case'; 
        ChildCase.Description = 'Test Parent Case'; 
        insert ChildCase; 
        
        Attachment atch = new Attachment();
        Blob bodyBlb=Blob.valueOf('test body');
        atch.Name='test attachment'; 
        atch.parentid=ParentCase.Id; 
        atch.Body=bodyBlb;
        insert atch;
        
        Test.startTest();
        PageReference pageRef = Page.ParentCaseAttachments;
        pageRef.getParameters().put('Id',ChildCase.Id);
        Test.setCurrentPage(pageRef);
        
        ApexPages.StandardController sc = new ApexPages.StandardController(ChildCase);
        CaseListController ext = new CaseListController(sc);
        Test.stopTest();
    }
}

Any direction is appreciated!
  • September 11, 2018
  • Like
  • 0
Hi,
Can you please help me with test class


Class:

global with sharing class BatchToEndCarouselAnnouncementsScheduler extends BatchScheduler implements Schedulable
{
    global BatchToEndCarouselAnnouncementsScheduler()
    {
        super(10 /*minutes between attempts */, 'End Carousel Announcements');
    }
    
    global void execute(SchedulableContext sc)
    {
        schedule(new BatchToEndCarouselAnnouncements());
    }
}


Extended Class:

public with sharing abstract class BatchScheduler implements Schedulable
{
    @TestVisible static final Integer MAX_CONCURRENT_BATCH = 5;
    @TestVisible Integer minutesBeforeReschedule;
    @TestVisible String title;
    public BatchScheduler( Integer minutes, String title )
    {
        this.minutesBeforeReschedule = minutes;
        this.title = title;
    } 
    public void schedule( IBatchHelper helper, Integer batchSize )
    {
        Integer currentlyRunningBatches = [SELECT count() FROM AsyncApexJob WHERE JobType='BatchApex'
                                           AND (Status = 'Processing' OR Status = 'Preparing')];
        if( currentlyRunningBatches < MAX_CONCURRENT_BATCH )
        {
            BatchHandler batch = new BatchHandler( helper );
            Database.executeBatch( batch, batchSize );
        }
        else
        {
            scheduleRetry();
        }
    }

    public void schedule( IBatchHelper helper )
    {
        schedule( helper, 200 );
    }

    @TestVisible void scheduleRetry() 
    { 
        Datetime rescheduleDateTime = Datetime.now().addMinutes(minutesBeforeReschedule); 
        String timeForScheduler = rescheduleDateTime.format('s m H d M \'?\' yyyy'); 
        System.schedule(title + ' ' + timeForScheduler, timeForScheduler, this); 
    } 
}
  • September 11, 2018
  • Like
  • 0
can you please me to write test class on below code:
Apex code:

public class copycontact {
    public list<selectoption>account1{set;get;}
    public list<selectoption>account2{set;get;}
    public list<contact>contacts{set;get;}
    public String getListOfAccounts { get; set; }
    public id selectedaccountId1 {set;get;}
    public id selectedaccountId2 {set;get;}
    public list<id>selected ;
    public List<SelectOption> getListOfAccounts1()
    {
        List<Account> AccountList1 = [select id,Name from Account] ;
        System.debug('Accounts'+AccountList1.size());
        account1 = new List<SelectOption>();
        account1.add(new SelectOption( ' ' ,'---Select---'));
        for(Account acc : AccountList1 )
        {
            account1.add(new SelectOption(acc.id , acc.Name));
        }
        return account1 ;         
    }
    public List<SelectOption> getListOfAccounts2()
    {
        List<Account> AccountList2 = [select id,Name from Account] ;
        System.debug('Accounts'+AccountList2.size());
        account2 = new List<SelectOption>();
        account2.add(new SelectOption( ' ' ,'---Select---'));
        for(Account acc : AccountList2 )
        {
            account2.add(new SelectOption(acc.id , acc.Name));  
        }
        system.debug('java');
        return account2 ;  
    } 
    public  void clonecontacts(){
        system.debug('gsvdd');
        if(selectedaccountId1!=null){
            contacts=new list<contact>([select id,lastname from contact where accountid=:selectedaccountId1]);
            if(contacts.size()==0){
                system.debug('gsg'   );
               ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'No contacts to display'));
            }
            else{
                system.debug('dhg');
                list<contact>clist=new list<contact>();
                for(Contact con:contacts){
                    contact c=new contact();
                    c.lastname=con.LastName;
                    c.AccountId=selectedaccountId2;
                    clist.add(c);
                }
                insert clist;
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'successfully copied'));
            }
        }
    }
}
vf page:

<apex:page controller="copycontact">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection title="from Account" >
                <apex:OutputPanel >
                    <apex:selectList value="{!selectedaccountId1}" size="1" multiselect="false" >
                        <apex:selectOptions value="{!ListOfAccounts1}"  />
                    </apex:selectList>
                </apex:OutputPanel>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
            <apex:pageBlockSection title="to account">
                <apex:selectList value="{!selectedaccountId2}" size="1" multiselect="false"  >
                    <apex:selectOptions value="{!ListOfAccounts2}" />
                </apex:selectList>
            </apex:pageBlockSection> >
        </apex:pageBlock>
        <apex:commandButton value="clone" action="{!clonecontacts}"/>
        <apex:pageMessages ></apex:pageMessages>
    </apex:form>
</apex:page>
Hi All,
​         i want to create a trigger on Account to count number of opportinty and contact relateed to Account.
How to do it?
Any suggestion?
Can anyone provide test class for following VF PAGE . The requirement is to search text in account,,contact,lead.
Please Include minimum 5 Asserts and test cases for positive negative bulk scenarios.

-------------------------------------------------VF--------------------------------------------
<apex:page Controller="SOSLController">
  <apex:form >
    <apex:inputText value="{!searchStr}"/>
    <apex:commandButton value="Search in Account, Contact, Opportunity" action="{!search}" reRender="accountId,error,opportunityId,contactId" status="actStatusId"/>
    <apex:actionStatus id="actStatusId">
      <apex:facet name="start" >
      <img src="/img/loading.gif"/>                    
      </apex:facet>
    </apex:actionStatus>
  </apex:form>
    
  <apex:outputPanel title="" id="error">
    <apex:pageMessages ></apex:pageMessages>
  </apex:outputPanel>
  
  
  <apex:pageBlock title="Accounts" id="accountId">
    <apex:pageblockTable value="{!accountList }" var="accountVar">
      <apex:column value="{!accountVar.name}"/>
      <apex:column value="{!accountVar.Type}"/>
    </apex:pageblockTable>
  </apex:pageBlock>

  
 
  <apex:pageBlock title="Contacts" id="contactId">
    <apex:pageblockTable value="{!contactList}" var="contactVar">
      <apex:column value="{!contactVar.name}"/>
      <apex:column value="{!contactVar.email}"/>
    </apex:pageblockTable>
  </apex:pageBlock>
  
  
      
  
  <apex:pageBlock title="Opportunities" id="opportunityId">
    <apex:pageblockTable value="{!OpportunityList}" var="opportunityVar">
      <apex:column value="{!opportunityVar.name}"/>
      <apex:column value="{!opportunityVar.StageName}"/>
    </apex:pageblockTable>
  </apex:pageBlock>
</apex:page>
-------------------------------------------------Controller------------------------------------------

Public with sharing class SOSLController{
  Public List<Opportunity> OpportunityList {get;set;}
  Public List<contact> contactList{get;set;}
  Public List<account> accountList{get;set;}
    
  Public String searchStr{get;set;}
    Public SOSLController(){
    }
    /**
    Method:searchText 
    Description : Method use SOSL Query to search the text.
    @return : searchText or Error Message */
    Public List<List<sObject>> search(){
      OpportunityList = New List<Opportunity>();
      contactList = New List<contact>();
      accountList = New List<account>();
     
      String searchStr1 = '*'+searchStr+'*';
      String searchQuery = 'FIND \'' + searchStr1 + '\' IN Name FIELDS RETURNING  Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName)';
      List<List <sObject>> searchList = search.query(searchQuery);
      accountList = ((List<Account>)searchList[0]);
      contactList  = ((List<contact>)searchList[1]);
      OpportunityList = ((List<Opportunity>)searchList[2]);
      if(accountList.size() == 0 && contactList.size() == 0 && OpportunityList.size() == 0){
          apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Sory, no results returned with matching string..'));
          
      }
    return searchList;
    }
}
  • August 17, 2018
  • Like
  • 0
Hi,
   
   Below trigger is working fine on a single transaction can we change this code to handle bulk load logic. Please suggest me
  
Trigger convertToUSD on Opportunity (before update){
     
  Try 
   {
       List<String> oppiso = new List<String>();  
       List<date> cdate = new List<date>();
      
      for(Opportunity o : trigger.new) 
        {
         oppiso.add(o.CurrencyIsoCode);
         cdate.add(o.closedate);
        }
    
        Double cts = [SELECT ConversionRate FROM DatedConversionRate 
                 where isocode IN :oppiso and 
                       startdate <= :cdate 
                 order by startdate desc limit 1].conversionRate;
                 
                  
       for(Opportunity ops : trigger.new) 
       {
        ops.CURRENCY_RATE__c = cts;
       }
    }
 
    catch (Exception e)
    {
        system.debug(e);
        for(Opportunity ops : trigger.new) 
        {
        ops.CURRENCY_RATE__c = null;
        }
    }  
}
Thanks
Sam
 
Hi There,

I've created a visualforce page based on a custom object and an extension which enables this to be opened from the account screen. 

Whenever I click "Save", I am redirected back to the account I invoked the visualforce page, however the record I created on the visualforce doesn't appear to be saving. 

 VF page:
<apex:page StandardController="Account" extensions="accountProp" sidebar="false">
    <apex:sectionHeader title="Edit AccountProperty" />
    <apex:form >
        <apex:pageBlock title="Edit AccountProperty" id="thePageBlock" mode="edit">
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>
            <apex:actionRegion >
                <apex:pageBlockSection title="Property Information" columns="1">
                    
                    <apex:pageBlockSectionItem >                       
                        <apex:outputLabel value="Property_Name__c"/>
                        <apex:outputPanel >                            
                            <apex:inputField value="{!objB.Property_Name__c}">
                                <apex:actionSupport event="onchange" rerender="thePageBlock"
                                                    status="status"/>
                            </apex:inputField>
                            <apex:actionStatus startText="applying value..." id="status"/>
                        </apex:outputPanel>
                    </apex:pageBlockSectionItem>
                </apex:pageBlockSection>
            </apex:actionRegion>
            <apex:pageBlockSection title="SVU Channel" columns="1"
                                   rendered="{!objB.Property_Name__c == 'Sunrise ID'}">
                <apex:inputField value="{!ObjB.Account__c}" required="true"/>
                <apex:inputField value="{!objB.Sunrise_ID__c}" required="true"/>
                <apex:inputField value="{!objB.Start_Date__c}" required="true"/>
                <apex:inputField value="{!objB.Implementation_Date__c}" required="true"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="SVU Channel" columns="1"
                                   rendered="{!objB.Property_Name__c == 'SVU Site ID'}">
                <apex:inputField value="{!objB.Account__c}" required="true"/>
                <apex:inputField value="{!objB.SVU_SITE_ID__c}" required="true"/>
                <apex:inputField value="{!objB.Start_Date__c}" required="true"/>
                <apex:inputField value="{!objB.Implementation_Date__c}" required="true"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:

public with sharing class accountProperty {
    
    ApexPages.StandardController sc;
    public Account_Property__c objB {get; set;}
    
    public accountProperty(ApexPages.StandardController sc)
    {
        this.sc = sc;
        objB = new Account_Property__c();
    }
    
    public ApexPages.PageReference SaveBoth()
    {
        insert objB;
        return sc.Save();
    }

}
I want output or not output some tag in visualforce page.
How can use if else?
ex:
<apex:repeat value="{!MapProducts[ikey]}" var="item">
                              {!if(item.id==0)}
                               <div class="columnnull">
                                   
                                </div> 
                              {!else}
                              <div class="column">                           
                                  <div class="zoomimage"> 
                                 </div>
                              </div>

 
How to write Test Class for dependent picklist methods?
  
 @AuraEnabled
    public static List<String> getDepStates(String objectType, String parentField, String childField,String search){    
        List<String> optionStates = new List<String>();
        PicklistFieldController controller = new PicklistFieldController();
        Map<String,List<String>> valueMap = PicklistFieldController.getDependentOptionsImpl(objectType,parentField,childField);
        for(String contr : valueMap.keySet()){
           // System.debug('CONTROLLING FIELD : ' + contr);
            //System.debug('DEPENDENT VALUES ...  : ' + valueMap.get(contr));
            if(search==contr){
                optionStates=valueMap.get(contr);
            }
        }
        return optionStates;
    }
    @AuraEnabled
    public static List<String> getPickList(String field,String objectName){    
        List<String> lstPickvals=new List<String>();
        Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objectName);
        Sobject Object_name = targetType.newSObject();
        Schema.sObjectType sobject_type = Object_name.getSObjectType(); 
        Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); 
        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); 
        List<Schema.PicklistEntry> pick_list_values = field_map.get(field).getDescribe().getPickListValues(); 
        for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
            lstPickvals.add(a.getValue());//add the value  to our final list
        }        
        return lstPickvals;
    }
   
}
I am changing one particular  field by checking lastmodifeddate in my code.All works fine but i am struck with test class.I am chnaging multiple records from multiple objects so my batch class looks like below.
 
global class editrecords implements Database.Batchable<string>, Schedulable{
global boolean bool = false;

global Iterable<string> start(Database.BatchableContext ctx) {
    return new list<String> { 'CO__c', 'CO2__c', 'CO3__c','CO4__c'};
}
global void execute(Database.BatchableContext ctx, list<string> listObj) {
    list<sObject> editrecords = new list<sObject>();
    for(string strObjName : listObj) {
        for(sObject objsObject : database.query('Select Id from ' + strObjName + ' where LastModifiedDate < LAST_N_DAYS:36')) {
                editrecords.add(objsObject);
            else {
                b = true;
                break;
            }
        }
    }
    update editrecords;
}
global void finish(Database.BatchableContext ctx) {

}        global void execute(SchedulableContext sc){
         Database.executebatch(new editrecords ());    
    }
}

my test class is as below which get 58% of coverage.How can i get lastmodified date and cover rest of code.please help.
 
@isTest
Public class testeditrecords{

    static testMethod void testMethod1(){

        CO__c CO =new CO__c(Name='testdata');
        insert CO;
        CO2__c co2 =new 
  co2__c(Name='testdata');
        insert co2;
        Co3__c co3 =new Co3__c(Name='test2');
        insert co3;

       for(CO__c c:[Select ID from CO__c where createddate=TODAY]){
        Test.startTest();
       
        editrecords obj = new editrecords();
        Database.executeBatch(obj);
        Test.stopTest();       
        }
   } 
}

 
Hello,

The business requirement is to have a lookup relation ship between a Contract and Opportunity. A field on the opportunity must get the SUM of a custom field on the Contracts which belong to the opportunity. I use the @future annotation to increase the CPU time, however, I get an error "Attempt to de-reference a null object".

Here's the code. I got the error on line 6 where I define the Set<ID>
public class contractRollUpCLASS {
    @future
    public static void calculate() {
  
    //limit the size of list by using Sets which do not contain duplicate elements.
    Set<ID> oppIds = new Set<ID>();

    
    //when adding new or updating existing contracts.
    if(trigger.isInsert || trigger.isUpdate) {
        
        for(Contract con : (List<Contract>)trigger.new) {
        
            if(con.Is_Obsolete__c == false)
            oppIds.add(con.Renewal_Opportunity__c);
        }
    }
    
    
    //when deleting contracts.
    if(trigger.isDelete){
        
        for(Contract con : (List<Contract>)trigger.old ) {
           if(con.Is_Obsolete__c == false)
            oppIds.add(con.Renewal_Opportunity__c);
        }
    } 
    System.debug('***************NUMBER OF IDS ************** : '+ String.ValueOf(oppIds.size()));
    
    //Map will contain one Opportunity Id to one sum value.
    map<Id, Double> OpportunityMap = new Map<Id,Double>();
    
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    
    //aggregate result.
    for(AggregateResult q : [SELECT Renewal_Opportunity__c, SUM(Latest_PD_Renewal_Amount__c) sumLatest FROM Contract WHERE Renewal_Opportunity__c IN : oppIds AND Latest_PD_Renewal_Amount__c != null GROUP BY Renewal_Opportunity__c]) {
        OpportunityMap.put((Id)q.get('Renewal_Opportunity__c'),(Double)q.get('sumLatest'));
    }
    
    for(Opportunity opp : [SELECT Id, Annual_Maintenance_Value__c FROM Opportunity WHERE Id IN : oppIds]) {

        Double sumLatestPD = OpportunityMap.get(opp.Id);
        opp.Annual_Maintenance_Value__c = sumLatestPD;
        oppsToUpdate.add(opp);     
    }    
    update oppsToUpdate;   
    
}
}

Any help would be much appreciated.
Angel
 
@RestResource(urlMapping='/Merchandise/*')
global with sharing class MerchandiseResource {

private class Attach {
    String Body;
    String ContentType;
    String Name;
}
private class Merchandise {
    Merchandise__c merchandise;
    list<Attach> attachments;
} 

@HttpPost
global static String doPost() {
    //json will be taken directly from RestContext
    Merchandise container = (Merchandise)System.JSON.deserialize(
        RestContext.request.requestBody.tostring(), 
        Merchandise.class);

    Merchandise__c merch = container.merchandise;
    insert merch;

    list<attachment> attachmentToInsert = new list<attachment>();

    for (Attach att :container.attachments) {
        attachmentToInsert.add(
            new Attachment(parentId = merch.Id, name = att.name, 
                           ContentType = att.ContentType, 
                           Body = EncodingUtil.base64Decode(att.body)));
    }
    insert attachmentToInsert;

    return merch.id;
}}

Can anyone suggest me a test class for this above code.
I send the following json.
 
{
    "merchandise": {
        "Name": "Eraser"
    },
    "attachments": [{
        "Body": "d29ybGQ=",
        "ContentType": "text/plain",
        "Name": "hello.txt"
    }, {
        "Body": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY3growIAAycBLhVrvukAAAAASUVORK5CYII=",
        "ContentType": "image/png",
        "Name": "picture.png"
    }]
}


I also tried the below test class,
 
@isTest
public class TesMerchandiseResource 
 {
    
     private Static testMethod void testFunction()
     {


System.RestContext.request = new RestRequest();
        System.RestContext.response = new RestResponse();
        RestContext.request.requestBody =blob.valueof('{}');

		
		 Account accountDetails = new Account();
        accountDetails.name = 'test name';
        upsert accountDetails;
		
 Attachment attachIt = new Attachment();
        attachIt.Name = 'test_attch';
        attachIt.ParentId = accountDetails.id;
        Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
      attachIt.body=bodyBlob;
	  
	   RestContext.request.requestBody =blob.valueof('{     "merchandise": {         "Name": "Eraser"     },     "attachments": [{         "Body": "d29ybGQ=",         "ContentType": "text/plain",         "Name": "hello.txt"     }, {         "Body": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY3growIAAycBLhVrvukAAAAASUVORK5CYII=",         "ContentType": "image/png",         "Name": "picture.png"     }] }');
        MerchandiseResource .doPost();

}

}

Still I get error "Attempt to de-reference a null object" in the line ​"for (Attach att :container.attachments) {"

Thanks in Advance,
Leafen.
 
From child-Parent soql
----------------------------
Parent = college
child =student(lookup with parent)
relation =Students

written query as

for(Student__c s:[select Name,college__r.Name,CollegeName__c from student__c])
{
  system.debug('student Name:'+s.Name+'     college Name:'+s.college__r.Name);
}

but error as

Line: 3, Column: 18
select Name,college__r.Name,CollegeName__c from ^ ERROR at Row:1:Column:13 Didn't understand relationship 'college__r'
I got to know that , Salesforce has recently introduced the Platform Developer 1 certification (DEV450) to replace the Developer (DEV401) certification. All practitioners, with the DEV401 certification, must complete the DEV450 exam during 2016 to retain a Salesforce developer certification.

Is this true as i dnt not got any email from salesforce / webassessvor that if you will not give the DEV450 exam then your DEV401 certifcate will expire ?
 
When i am posting code "" is not printing. And Some code is removing automatically. 

Any idea . It look like some issue ?
External Lookup Relationship could now be setup between external objects and Salesforce object.
External Object - They are same as custom objects but used to map to data located outside Salesforce.
External object take data from External source and External source obviously has its own DB. 
To create external object : From Setup, click Develop | External Objects.
To create external Data source : Develop | External data source
 
I got to know that , Salesforce has recently introduced the Platform Developer 1 certification (DEV450) to replace the Developer (DEV401) certification. All practitioners, with the DEV401 certification, must complete the DEV450 exam during 2016 to retain a Salesforce developer certification.

Is this true as i dnt not got any email from salesforce / webassessvor that if you will not give the DEV450 exam then your DEV401 certifcate will expire ?
 
I'm running into the dreaded too many query rows error on an iterable batch.  No matter the batch size I use, it immediately errors out; even if I set the batch size to 1.  Looking at the logs, it seems to happen while still in the start() method.

This is driving me nuts - I look forward to your insights...

Thanks!

Here's the batch...
global with sharing class update_MBI implements Database.Batchable<AggregateResult> {
	global update_MBI() { }
    global string mbiQuery = 'select account__c, sum(spend__c) spendLast12 from spend__c where age__c < 0 and age__c >= -12 group by account__c ';

	global Iterable<AggregateResult> start(Database.BatchableContext BC) {  
		return new mbiIterable(mbiQuery);
	}

   	global void execute(Database.BatchableContext BC, List<AggregateResult> scope) {
		list<account> u = new list<account>();
		for (AggregateResult ar : scope){
			id acctID = id.valueOf(string.valueOf(ar.get('account__c')));
			decimal newMBI = decimal.valueOf(string.valueOf(ar.get('spendLast12'))) / 12;
			u.add(new account(id=acctID, MBI_Monthly_Spend_Current__c = newMBI));
		}
		update u;
	} 

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

The Iterable 
public with sharing class mbiIterable implements Iterable<AggregateResult> {
    private String query;

    public mbiIterable(String soql){
		query = soql;
    }

    public Iterator<AggregateResult> Iterator(){
		return new mbiIterator(query);
    }
}

The iterator
public class mbiIterator implements Iterator<AggregateResult> {

  AggregateResult[] results { get;set; }
  Integer index { get;set; }

  public mbiIterator(String query) {
	  index = 0;
	  results = Database.query(query);
  }

  public Boolean hasNext(){
	  return results != null && !results.isEmpty() && index < results.size();
  }

  public AggregateResult next() {
	  return results[index++];
  }
}

 
Hi guys, please give a good starting point for practicing the salesforce development. Is the tutorial videos are much beneficial or articals or something else? Is this platform needs any prerequest to start the practice or anyone can use?
Hello,

I am running into a strange issue - I have created a Record Update QuickAction on Contact object, which we have added on page layouts for users to be able to anonymize the contact record (for GDPR compliance purposes).  This QuickAction uses Predefined Field Values to remove / obfuscate data on certain contact fields that contain personal info (Name, Email, Phone #, etc.)  The action is working fine when invoked on a single record from the UI.

As part of our Sandbox refresh strategy, I am trying to invoke the same QuickAction via apex code to anonymize ALL contacts as a post-refresh task (Apex class that implements SandboxPostCopy interface).  Since it should run on all records, I am invoking it from a Batchable class.  

What I am running into is that in my test class, it appears in debug logs that invoking the QuickAction on the batch of records is successful, but when I re-query those records to do an assert to make sure they were updated, the query shows that the records have NOT been updated by the Quick Action.

Here is some sample code to illustrate:
 
global class SandboxBuild implements SandboxPostCopy{
	final String CLASSNAME = '\n\n**** SandboxBuild.METHODNAME()';
	global void runApexClass(SandboxContext context){
		final string METHODNAME = CLASSNAME.replace('METHODNAME','runApexClass');
		system.debug(LoggingLevel.INFO, METHODNAME.replace('**** ', '**** Inside '));

        SandboxBuildHelper sbh = new SandboxBuildHelper();
		sbh.anonymizeContacts();
	}
}
public class SandboxBuildHelper {

    public void anonymizeContacts() { 
        // Query for selecting the contacts to anonymize - in this case ALL contacts
        String query = 'SELECT Id FROM Contact Limit 5';
        
        // Invoke the batch job.
        BatchGDPRAnonymizeContacts bAnon = new BatchGDPRAnonymizeContacts(query);
        Id batchprocessid = Database.executeBatch(bAnon);
        System.debug('Returned batch process ID: ' + batchProcessId);
    }

}
 
global class BatchGDPRAnonymizeContacts implements Database.Batchable<sObject> {
	
	global final String query;
	
	global BatchGDPRAnonymizeContacts(String q) {
		query=q;
	}
		
	global Database.QueryLocator start(Database.BatchableContext BC) {
		return Database.getQueryLocator(query);
	}

   	global void execute(Database.BatchableContext BC, List<sObject> scope) {
		
        List<QuickAction.QuickActionRequest> reqs = new List<QuickAction.QuickActionRequest>();
		List<QuickAction.QuickActionResult> results = new List<QuickAction.QuickActionResult>();
        for(sObject s : scope){
			Contact c = (Contact)s;
			system.debug('Contact: '+ c.FirstName+' '+c.LastName+' - '+c.Email+' - '+c.Phone);
			QuickAction.QuickActionRequest req = new QuickAction.QuickActionRequest();
        	req.quickActionName = Schema.Contact.QuickAction.GDPR_Anonymize_Contact;
			req.record = c;
        	reqs.add(req);
		}
		results = QuickAction.performQuickActions(reqs);
		for(QuickAction.QuickActionResult r: results){
			system.debug('getIds(): '+r.getIds());
			system.debug('getSuccessMessage(): '+r.getSuccessMessage());
			system.debug('isCreated(): '+r.isCreated());
			system.debug('isSuccess(): '+r.isSuccess());
			system.debug('getErrors(): '+r.getErrors());
		}
	}
	
	global void finish(Database.BatchableContext BC){
		// Get the ID of the AsyncApexJob representing this batch job
		// from Database.BatchableContext.
		// Query the AsyncApexJob object to retrieve the current job's information.
		AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
			TotalJobItems, CreatedBy.Email
			FROM AsyncApexJob WHERE Id = :BC.getJobId()];

		system.debug('Apex BatchGDPRAnonymizeContacts ' + a.Status);
		system.debug('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+ a.NumberOfErrors + ' failures.');
	}
	
}
 
@isTest
private class BatchGDPRAnonymizeContacts_Test {
    
    @isTest static void testbatch() {
        // create 200 test contacts - this simulates one execute.
        // Important - the Salesforce.com test framework only allows you to
        // test one execute
        List <Contact> cList = new List<Contact>();
        Integer numContacts = 5;
            for(integer i = 0; i<numContacts; i++){
                Contact c = new Contact (FirstName='test', LastName='Contact'+i, Email='test'+i+'@test.com', Phone='+1208555000'+i);
                cList.add(c);
            }
        
        insert cList;
        
        Test.StartTest();
        String query = 'SELECT ID, FirstName, LastName, Email, Phone ' +
                    'FROM Contact ' +
                    ' LIMIT ' + numContacts;
        BatchGDPRAnonymizeContacts batch = new BatchGDPRAnonymizeContacts(query);
        
        ID batchprocessid = Database.executeBatch(batch, 50);
        Test.StopTest();
        List<Contact> cListAnon = [Select Id, FirstName, LastName, Email, Phone from Contact];
        system.debug('cListAnon: ' + cListAnon);
        
        System.AssertEquals( numContacts, database.countquery('SELECT COUNT() FROM Contact WHERE FirstName=\'ANONYMOUS\''));
        
    }
}

Exceprts of DEBUG output when running the Apex Test:
 
12:50:12.990 (4209501390)|CODE_UNIT_STARTED|[EXTERNAL]|01pq0000000ajd6|BatchGDPRAnonymizeContacts
12:50:12.990 (4215187082)|SOQL_EXECUTE_BEGIN|[11]|Aggregations:0|SELECT ID, FirstName, LastName, Email, Phone FROM Contact  
12:50:12.990 (4299212112)|SOQL_EXECUTE_END|[11]|Rows:5
12:50:12.990 (4325480890)|CODE_UNIT_FINISHED|BatchGDPRAnonymizeContacts
12:50:12.990 (4326373234)|CODE_UNIT_STARTED|[EXTERNAL]|01pq0000000ajd6|BatchGDPRAnonymizeContacts
12:50:12.990 (4347406438)|CODE_UNIT_STARTED|[EXTERNAL]|01pq0000000ajd6|BatchGDPRAnonymizeContacts
12:50:12.990 (4348454925)|USER_DEBUG|[20]|DEBUG|Contact: test Contact0 - test0@test.com - +12085550000
12:50:12.990 (4348661312)|USER_DEBUG|[20]|DEBUG|Contact: test Contact1 - test1@test.com - +12085550001
12:50:12.990 (4348743660)|USER_DEBUG|[20]|DEBUG|Contact: test Contact2 - test2@test.com - +12085550002
12:50:12.990 (4348811920)|USER_DEBUG|[20]|DEBUG|Contact: test Contact3 - test3@test.com - +12085550003
12:50:12.990 (4348877642)|USER_DEBUG|[20]|DEBUG|Contact: test Contact4 - test4@test.com - +12085550004
12:50:12.990 (4349377319)|DML_BEGIN|[27]|Op:PerformQuickAction|Type:QuickActionResult|Rows:5
.
.
.
.
12:50:12.990 (4681351512)|DML_END|[27]
12:50:12.990 (4681899567)|USER_DEBUG|[29]|DEBUG|getIds(): (003q000000w1HK0AAM)
12:50:12.990 (4681941852)|USER_DEBUG|[30]|DEBUG|getSuccessMessage(): Contact details successfully anonymized.
12:50:12.990 (4681982207)|USER_DEBUG|[31]|DEBUG|isCreated(): false
12:50:12.990 (4682015050)|USER_DEBUG|[32]|DEBUG|isSuccess(): true
12:50:12.990 (4682105172)|USER_DEBUG|[33]|DEBUG|getErrors(): ()
12:50:12.990 (4682171498)|USER_DEBUG|[29]|DEBUG|getIds(): (003q000000w1HK1AAM)
12:50:12.990 (4682187044)|USER_DEBUG|[30]|DEBUG|getSuccessMessage(): Contact details successfully anonymized.
12:50:12.990 (4682204942)|USER_DEBUG|[31]|DEBUG|isCreated(): false
12:50:12.990 (4682229456)|USER_DEBUG|[32]|DEBUG|isSuccess(): true
12:50:12.990 (4682260353)|USER_DEBUG|[33]|DEBUG|getErrors(): ()
12:50:12.990 (4682313526)|USER_DEBUG|[29]|DEBUG|getIds(): (003q000000w1HK2AAM)
12:50:12.990 (4682328104)|USER_DEBUG|[30]|DEBUG|getSuccessMessage(): Contact details successfully anonymized.
12:50:12.990 (4682345912)|USER_DEBUG|[31]|DEBUG|isCreated(): false
12:50:12.990 (4682361731)|USER_DEBUG|[32]|DEBUG|isSuccess(): true
12:50:12.990 (4682389503)|USER_DEBUG|[33]|DEBUG|getErrors(): ()
12:50:12.990 (4682436899)|USER_DEBUG|[29]|DEBUG|getIds(): (003q000000w1HK3AAM)
12:50:12.990 (4682450390)|USER_DEBUG|[30]|DEBUG|getSuccessMessage(): Contact details successfully anonymized.
12:50:12.990 (4682467749)|USER_DEBUG|[31]|DEBUG|isCreated(): false
12:50:12.990 (4682483932)|USER_DEBUG|[32]|DEBUG|isSuccess(): true
12:50:12.990 (4682510753)|USER_DEBUG|[33]|DEBUG|getErrors(): ()
12:50:12.990 (4682555396)|USER_DEBUG|[29]|DEBUG|getIds(): (003q000000w1HK4AAM)
12:50:12.990 (4682568987)|USER_DEBUG|[30]|DEBUG|getSuccessMessage(): Contact details successfully anonymized.
12:50:12.990 (4682585831)|USER_DEBUG|[31]|DEBUG|isCreated(): false
12:50:12.990 (4682602455)|USER_DEBUG|[32]|DEBUG|isSuccess(): true
12:50:12.990 (4682629221)|USER_DEBUG|[33]|DEBUG|getErrors(): ()
12:50:12.990 (4682654145)|CODE_UNIT_FINISHED|BatchGDPRAnonymizeContacts
12:50:12.990 (4718160419)|CODE_UNIT_FINISHED|BatchGDPRAnonymizeContacts
12:50:12.990 (4719016441)|CODE_UNIT_STARTED|[EXTERNAL]|01pq0000000ajd6|BatchGDPRAnonymizeContacts
12:50:12.990 (4726103588)|SOQL_EXECUTE_BEGIN|[44]|Aggregations:0|SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :tmpVar1
12:50:12.990 (4733869475)|SOQL_EXECUTE_END|[44]|Rows:1
12:50:12.990 (4734225747)|USER_DEBUG|[48]|DEBUG|Apex BatchGDPRAnonymizeContacts Completed
12:50:12.990 (4734367728)|USER_DEBUG|[49]|DEBUG|The batch Apex job processed 1 batches with 0 failures.
12:50:12.990 (4741437910)|CODE_UNIT_FINISHED|BatchGDPRAnonymizeContacts
12:50:12.990 (4743061969)|SOQL_EXECUTE_BEGIN|[25]|Aggregations:0|SELECT Id, FirstName, LastName, Email, Phone FROM Contact
12:50:12.990 (4747198855)|SOQL_EXECUTE_END|[25]|Rows:5
12:50:12.990 (4747514612)|USER_DEBUG|[26]|DEBUG|cListAnon: (Contact:{Id=003q000000w1HK0AAM, FirstName=test, LastName=Contact0, Email=test0@test.com, Phone=+12085550000}, Contact:{Id=003q000000w1HK1AAM, FirstName=test, LastName=Contact1, Email=test1@test.com, Phone=+12085550001}, Contact:{Id=003q000000w1HK2AAM, FirstName=test, LastName=Contact2, Email=test2@test.com, Phone=+12085550002}, Contact:{Id=003q000000w1HK3AAM, FirstName=test, LastName=Contact3, Email=test3@test.com, Phone=+12085550003}, Contact:{Id=003q000000w1HK4AAM, FirstName=test, LastName=Contact4, Email=test4@test.com, Phone=+12085550004})
12:50:12.990 (4747700346)|SOQL_EXECUTE_BEGIN|[29]|Aggregations:0|SELECT COUNT() FROM Contact WHERE FirstName='ANONYMOUS'
12:50:12.990 (4752840759)|SOQL_EXECUTE_END|[29]|Rows:0
12:50:12.990 (4752943948)|EXCEPTION_THROWN|[29]|System.AssertException: Assertion Failed: Expected: 5, Actual: 0
12:50:12.990 (4753035742)|FATAL_ERROR|System.AssertException: Assertion Failed: Expected: 5, Actual: 0

Class.BatchGDPRAnonymizeContacts_Test.testbatch: line 30, column 1
12:50:12.990 (4753045670)|FATAL_ERROR|System.AssertException: Assertion Failed: Expected: 5, Actual: 0

Based on the above, it seems that the Batch ran successfully and the QuickAction executed successfully on the batch of 5 records, but the re-query afterwards (just before the AssertEquals statement) shows the original data before the update.  

Any ideas what I might be missing here?
How to write a trigger when case status is closed then all task should be completed and when all task are completed then case should get closed?
I am trying to de-activate an apex trigger in production but it keeps failling. I have tried 2 different methods:

1. De-activating in sandbox and pushing to production
2. Using force.com IDE to delete. I am able to delete in my sandbox environment but I keep receiving an error when I try to deploy it to production.

Here is the error:

User-added image 
Hello,

I tried "Restrict Login IP Ranges" challenge  on my org but i got the below error. Any suggestions or help pls..

There was an unexpected error while verifying this challenge. Usually this is due to some pre-existing configuration or code in the challenge Org. We recommend using a new Developer Edition (DE) to check this challenge. If you're using a new DE and seeing this error, please post to the developer forums and reference error id: GVUJGQSW


There was an unexpected error while verifying this challenge. Usually this is due to some pre-existing configuration or code in the challenge Org. We recommend using a new Developer Edition (DE) to check this challenge. If you're using a new DE and seeing this error, please post to the developer forums and reference error id: UBKSBZND
 
I've written this scheduable apex class but I can't figure out how to write a test class. 
global class UpdateCSMTeam implements Schedulable {
    
    global void execute(SchedulableContext ctx) {

    // Create a list of the accounts to update
    List<Account> myList = new List<Account>();

    // Create a list of all the customer accounts
    List<Account> accountList = [SELECT Id, Account_Manager__c FROM Account WHERE Type = 'Customer'];

    for (Account acc : accountList){
    	// one
    	if(acc.Account_Manager__c == '0051I0000027OCuQAM') {
    		acc.Onboarding_Specialist__c = '0051I0000029k0yQAA';
    		acc.Product_Specialist__c = '0051I0000027ODJQA2';

    		myList.add(acc);
    	}
    	// two
    	if(acc.Account_Manager__c == '0051I0000029k3sQAA') {
    		acc.Onboarding_Specialist__c = '0051I0000029k0ZQAQ';
    		acc.Product_Specialist__c = '0051I000002Q8XaQAK';

    		myList.add(acc);
    	}
    	// three
    	if(acc.Account_Manager__c == '0051I000002baVoQAI') {
    		acc.Onboarding_Specialist__c = '0051I000002slVdQAI';
    		acc.Product_Specialist__c = '0051I000002QShlQAG';

    		myList.add(acc);
    	}
    	// four
    	if(acc.Account_Manager__c == '0051I000002s0dpQAA') {
    		acc.Onboarding_Specialist__c = '0051I000002QPrUQAW';
    		acc.Product_Specialist__c = '0051I0000027ODOQA2';

    		myList.add(acc);
    	}
    	// five
    	if(acc.Account_Manager__c == '0051I000002QPrTQAW') {
    		acc.Onboarding_Specialist__c = '0051I000002s0dqQAA';
    		acc.Product_Specialist__c = '0051I000002stE6QAI';

    		myList.add(acc);
    	}
    }

    update myList;

    }
}
Any help appreciated!
To get paramater I used this code..

<aura:component implements="lightning:isUrlAddressable,lightning:hasPageReference" >
{!v.pageReference.state}

but, {!v.pageReference} is null.

how can I get a URL paramater in the lightning component????

public with sharing class SurveyUtil {


public Boolean hasSites() {
return Schema.getGlobalDescribe().keySet().contains('site');
}
public List<SurveySiteInfo> getSiteList() {
List<SurveySiteInfo> ret = new List<SurveySiteInfo>();
if (!hasSites()) {
return ret;
}
List<Sobject> sitesResults = Database.query('Select Name, Subdomain, UrlPathPrefix from Site Where Status = \'Active\'');
for (Sobject current : sitesResults) {
ret.add(new SurveySiteInfo((String)current.get('Name'), (String)current.get('UrlPathPrefix'), (String)current.get('Subdomain')));
}
return ret;
}
public class SurveySiteInfo {
public String name { get; set; }
public String prefix { get; set; }
public String subdomain {get; set; }
public SurveySiteInfo(String name, String prefix, String subdomain) {
this.name = name;
this.prefix = prefix;
this.subdomain = subdomain;
}
}
Hello,

I have swagger of extension .yml
How can i import it in Postaman and test it ?

Thank you for suggestions

At Dreamforce 18 we were told that if we speak to our account manager, then we can get access to the beta program for VSCode, which will allow us to use VSCode with non-DX orgs. - Our account manager has said that we should ask around on the forums.

From gihub https://github.com/forcedotcom/salesforcedx-vscode/wiki/Develop-Against-Any-Org-in-Visual-Studio-Code
it says it all in the link title! Yet when we come to context clicking on the package.xml we do not see the SFDX: Retreive Source from Org.

Maybe our account manager is just rubbish...

Does anyone know who I would have to email or send a box of chocolates to in return for access to the VSCode beta program?

Thanks!

Tim

HI All,

The salesforce org which I'm working on right now is currently using Classic. They want a custom button to invoke an apex class - which sits on the page layout.

I believe the best practice is to create a custom button which directs to a  VisualForce page, behind the scenes, to invoke an apex class. Is this still the best way to go, if the client is going to move to lightning soon?

Thanks
I am new to Salesforce and trying to create Big object first on sandbox. We are archiving the records from a Custom object to Big Object. The custom object has all kind of fields such as 
- Date/Time
- Picklist
- Number
- Formula
- Checkbox
- URL
- Lookup
- Percent
- Master-Detail and more... 

Does Big object supports all the mentioned data types? I went through some documentation avaialble to deploy the Big object but was not able to find the answer to this Question.
Thank you
When I use the JSENCODE I have the following issue:
var accRegNumber = "{!Account.Registration_Number__c}";
var accName = "{!Account.Name}";
var accType = "{!Account.Custom_Filed_Type__c}";
var accRate = "{!Account.Custom_Filed_Rate__c}";
var accId = "{!Account.Id}";

accRegNumber = {!JSENCODE(accRegNumber)};
accName = {!JSENCODE(accName)};
accType = {!JSENCODE(accType)};
accRate = {!JSENCODE(accRate)};
accId = {!JSENCODE(accId)};
Error: Field accRegNumber does not exist. Check spelling.

Could you please advise why adding {!JSENCODE(accRegNumber)}; to accRegNumber variable is giving an error message?
I have an Opportunity record and it has Product (OpportunityLineItem) related list and Placement related list.
if Opportunity is Closed Won and it has Product record, the trigger should create a Placement record (its fields are based on Opportunity and Product fields).

It is creating a record BUT the problem is:
For example existing Product record is “Book”, so it creates 1 Placement record.
if I add another Product again, for example “Album”, the Opportunity will update and create another Placement record from Book and creates 1 Placement record for Album. If I add Product again, and once the Opportunity updates, it creates another 1 Placement record again for Book and Album.

how can I prevent it from creating duplicate records?
Here’s my code:
trigger CreatePlacement on Opportunity (after insert, after update) {
	Set <Id> oppIds = new Set<Id>();
    for (Opportunity opty : Trigger.new) {
        oppIds.add(opty.Id);
    }

    List<Opportunity> oLst = [SELECT Id, Account.Name, IsClosed, IsWon, CloseDate FROM Opportunity WHERE Id IN :oppIds];
    List<OpportunityLineItem> oliList = [SELECT Id, ProductP.Name, TotalPrice, Quantity, Opportunity.Name FROM OpportunityLineItem WHERE OpportunityId IN :oppIds]; 
    List<Placement__c> pList = new List<Placement__c>();
    for (Opportunity o : oLst) {
            if (o.IsClosed == True && o.IsWon == True) {
                for (OpportunityLineItem li : oliList) {
                    Placement__c p = new Placement__c();
                    p.Name = o.Account.Name +' '+ li.Product2.Name;
                    p.Opportunity__c = o.Id;
                    p.Product__c = li.ProductP.Name;
                    p.Qty__c = li.Quantity;
                    pList.add(p);
                }
            }
    }
    if (pList.size() > 0) {
        upsert pList;
    }
}

Please reply. Nobody seems helping here..
Hello, I am new to APEX, Can someone tell me if this is possible to have duplicate Key in a MAP. I am adding element from a list to a map and when i print my map, i see duplicate value of the key. Here is how my map and its data items are defined.

public class ZTECase
    {
        public string OracleCaseNumber{get;set;}
    }
public class ZTEContact
    {
        public string FirstName{get;set;}
        public string LastName{get;set;}
        public string EmailAddress{get;set;}  
}

  map<ZTECase,ZTEContact> mapZTEData=new map<ZTECase,ZTEContact>
                      ZTECase objZTECase=new ZTECase();    
                      ZTEContact objZTEContact=new ZTEContact();    

In this map, we are adding  OracleCaseNumber and Contact info from Oracle Service Cloud. When i am printing this map post my addition, i see duplicate OracleCaseNumber which is my Key in the map ZTECase. Please suggest
 
Hi and thanks in Advance.  I was able to write a test code for my class, but need help.  This provides 5% coverage.

Class:
global with sharing class TMWSendOrderService 
{
    public class OrderResponse 
    {
        string OrderNumber;
        List<string> Comments = new List<string>();
        List<string> Errors = new List<string>();
        string CaseNumber;
    }
  
  public class FuelOrdered 
    {
    string Type;
    integer Amount;
  }
    
    public class TmwOrder 
    {
        string CaseNumber;
        Date DeliveryDate;
        string DeliveryTimeframe;
        string CompanyCode;
        string Origin;
    List<FuelOrdered> FuelList = new List<FuelOrdered>();
    List<string> ErrorsFound = new List<string>();
    }
  
    webservice static String SendToTmw(string cid) 
    {
    system.debug('cid: ' + cid);
        return SendOrderToTmw(cid);
    }
  
    private static string SendOrderToTmw(string cid)
    {

        if(String.isBlank(cid))
            return 'INVALID_PARAMETERS';
        
        // get list of cases that have not yet been sent to TMW and have a valid quantity
    List<Case> sfCases = [ SELECT Id, AccountId, CaseNumber, Origin, 
        RQ_Delivery_Date__c, RQ_Delivery_Timeframe__c, 
        Fuel1_Requested_Type__c, Fuel1_Requested_Amount__c, 
        Fuel2_Requested_Type__c, Fuel2_Requested_Amount__c, 
        Fuel3_Requested_Type__c, Fuel3_Requested_Amount__c, 
        Fuel4_Requested_Type__c, Fuel4_Requested_Amount__c
      FROM Case WHERE id = :cid 
      AND TMW_Order_Num__c = '' //AND SendtoTMW__c = false 
      AND ( 
        Fuel1_Requested_Amount__c > 0 OR Fuel2_Requested_Amount__c > 0 
                OR Fuel3_Requested_Amount__c > 0 OR Fuel4_Requested_Amount__c > 0 
            ) ]; 
        // Instantiate a new http object.  Create a list of cases and send to REST service
        if(sfCases.size() == 0)
            return 'This case requires: valid quantity, requested delivery time and timeframe, and cannot be a resubmission.';
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        Case sfCase = sfCases[0];
    // get company  code from translation table
    string companyCode = 
        [  
          SELECT Surrogate_ID__c FROM Translation_Table__c 
          WHERE IntegratedSite__c = :sfCase.AccountId LIMIT 1
        ].Surrogate_ID__c.replace('TMW-','');
        // populate case
        TmwOrder tmwOrder = new TmwOrder();
        tmwOrder.CaseNumber = sfCase.casenumber;
        tmwOrder.DeliveryDate = sfCase.RQ_Delivery_Date__c;
        tmwOrder.DeliveryTimeframe = sfCase.RQ_Delivery_Timeframe__c;
        tmwOrder.CompanyCode = companyCode;
        tmwOrder.Origin = sfCase.Origin;
        FuelOrdered item = new FuelOrdered();
        // create FuelOrdered list from requested types/amounts
        item.Type = sfCase.Fuel1_Requested_Type__c;
        item.Amount = Integer.valueOf(sfCase.Fuel1_Requested_Amount__c);
        if (item.Amount > 0) tmwOrder.FuelList.Add(item);
        item = new FuelOrdered();
        item.Type = sfCase.Fuel2_Requested_Type__c;
        item.Amount = Integer.valueOf(sfCase.Fuel2_Requested_Amount__c);
        if (item.Amount > 0) tmwOrder.FuelList.Add(item);
        item = new FuelOrdered();
        item.Type = sfCase.Fuel3_Requested_Type__c;
        item.Amount = Integer.valueOf(sfCase.Fuel3_Requested_Amount__c);
        if (item.Amount > 0) tmwOrder.FuelList.Add(item);
        item = new FuelOrdered();
        item.Type = sfCase.Fuel4_Requested_Type__c;
        item.Amount = Integer.valueOf(sfCase.Fuel4_Requested_Amount__c);
        if (item.Amount > 0) tmwOrder.FuelList.Add(item);
        string postString = JSON.serialize(tmwOrder);
        req.setBody(postString);
        req.setEndpoint('http://dev-tmw.sunocolp.com/api/CreateTMWOrder');
        req.setHeader('content-type','application/json');
        req.setTimeout(60000);
        req.setMethod('POST');
        //req.setCompressed(true);
        // Send the request, and return a response
        HttpResponse res = h.send(req);
        string bod = res.getBody();
        system.debug(bod);
        OrderResponse rsp = (OrderResponse)JSON.deserialize(bod, OrderResponse.class);
        system.debug('order response: ' + rsp);
        Case newCase;
        if (rsp.OrderNumber != null && rsp.OrderNumber !='')
        {
            // If Order was created, add order # to the case
            newCase = 
      [  
        Select Id, TMW_Order_Num__c, SFtoTMWSent__c, SendtoTMW__c  
                FROM Case 
                WHERE CaseNumber = :rsp.CaseNumber
            ];
            newCase.TMW_Order_Num__c = rsp.OrderNumber;
            newCase.SendtoTMW__c = true;
            newCase.SFtoTMWSent__c = date.today();
            update newCase;
        }
        else
        {
            // No order # was returned.  Mark case as sent to TMW.
            newCase = 
            [  
                 SELECT Id, SFtoTMWSent__c, SendtoTMW__c  
                 FROM Case 
                 WHERE CaseNumber = :rsp.CaseNumber
            ];
            newCase.SendtoTMW__c = true;
            newCase.SFtoTMWSent__c = date.today();
            update newCase;
        }
        // add case comments (if any)
        for (Integer i = 0; i < rsp.Comments.size(); i++)
        {
            CaseComment com = new CaseComment();
            com.ParentId = newCase.id;
            com.CommentBody = rsp.Comments[i];
            insert com;
        }        
        return 'Order submitted successfully!';
    }
}
---------------------------
Test Class:
@isTest
 
private class TMWSendOrderService_Test{
 
  @testSetup
 
  static void setupTestData(){
 
    test.startTest();
 
    Translation_Table__c translation_table_Obj = new Translation_Table__c(Integration_Status__c = false);
 
    Insert translation_table_Obj; 
 
    test.stopTest();
 
  }
 
   static testMethod void test_TmwOrder(){
 
    List<Translation_Table__c> translation_table_Obj  =  [SELECT Integration_Status__c, Name from Translation_Table__c];
 
    System.assertEquals(true,translation_table_Obj.size()>0);
 
    TMWSendOrderService obj01 = new TMWSendOrderService();
 
    TMWSendOrderService.OrderResponse obj11 = new TMWSendOrderService.OrderResponse();
 
    TMWSendOrderService.FuelOrdered obj21 = new TMWSendOrderService.FuelOrdered();
 
    TMWSendOrderService.TmwOrder obj31 = new TMWSendOrderService.TmwOrder();
 
  }
 
}

 
trigger updateAccountIfOppCustomer on Opportunity (after insert,after update) {
    List<Account>accToupdate=new List<Account>();
    List<Opportunity>opps = new List<Opportunity>();
    set<id>associatedAccid = new set<id>();
    for(Opportunity opp :trigger.new){
        associatedAccid.add(opp.AccountId);
        System.debug('associatedAccid'+opp.AccountId);
    }
    //Map<id,Account>Accmap=new Map<id,Account>
    opps =[Select id,Accountid,StageName,Account.Type From Opportunity Where Accountid =:associatedAccid];
    System.debug('Opportunity' +opps);
    for(Opportunity opp:opps){
        if(opp.StageName=='Closed Won-One Time'||opp.StageName=='Closed Won-Recurring'||opp.StageName=='Customer Reseller'){
            opp.Account.Type='Customer-Direct';
            accToupdate.add(opp.Account);
            System.debug('accToupdate'+opp.Account);
        }
        else{
            opp.Account.Type='Prospect';
           accToupdate.add(opp.Account);
        }
    }
    update accToupdate;
}
I was working on the Customize Your Login Process with My Domain module and I accidentally changed my domain of my Hands-On Org. Is it possible to change it back to what it was? I get an error message now when I try to launch my hands-on org. L

My former Hands On Org. URL is as follows: curious-badger-397879-dev-ed.my.salesforce.com

The domain I changed it to is: mylightsaber.dom-dev-ed.my.salesforce.com
 
NOT (ISPICKVAL( Transfer_ID__r.Transfer_Type__c , 'Store to WHS') AND (Shipping_Quantity__c > Serial_No__r.Quantity_available__c ))

I am getting ) missing in thie validation rule, Can someone help?

System.QueryException: List has more than 1 row for assignment to SObject
Class.AccountSearchUI.<init>: line 13, column 1

My VF Page

<apex:page standardController="Account" extensions="AccountSearchUI">
<head>
<title>Account Search UI</title>
<style type="text/css"> </style>
</head>

<body>
<table width="99%" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
    <tr>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
    </tr>
    <tr>
        <td bgcolor="#FFFFFF"></td>
        <td bgcolor="#FFFFFF"></td>
        <td bgcolor="#FFFFFF"></td>
      </tr>
    <tr>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
    </tr>
    <tr>
    <td bgcolor="#FFFFFF" valign="top">
        <table width="100%" border="0" align="center" cellpadding="1" cellspacing="0" class="tablemain">
            <tr><td height="1"></td></tr>
            <tr><td height="50" class="headingmain">&nbsp;Account Search UI</td></tr>
            <tr>
                <td align="center">
                  <table width="100%" border="0" cellspacing="0" cellpadding="1" class="tablemain">
                    <tr>
                      <td width="10%" height="23" class="headingsub1">Group Org Acc</td>
                      <td width="10%" height="23" class="headingsub1">Vertical</td>
                      <td width="10%" height="23" class="headingsub1">Account Name</td>
                      <td width="10%" height="23" class="headingsub1">Type</td>
                      <td width="10%" height="23" class="headingsub1">Owner Last Name</td>
                      <td width="10%" height="23" class="headingsub1">Client Rank</td>
                      <td width="10%" height="23" class="headingsub1">Account Plan</td>
                      <td width="10%" height="23" class="headingsub1">Last Modified</td>
                      <td width="10%" height="23" class="headingsub1">View Latest PDF</td>
                      <td width="10%" height="23" class="headingsub1">PDF Upload Date</td>
                    </tr>
                    <apex:repeat value="{!accPList}" var="cp">
                    <tr>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Group_Org__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Vertical__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Name}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Type}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Client_Rank__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Group_Org__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Vertical__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Name}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Type}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Client_Rank__c}"/></td>
                    </tr>
                    </apex:repeat>
          </table>
        </td>
        
      </tr>
    </table></td>
    <td bgcolor="#FFFFFF" valign="top"></td>
    <td bgcolor="#FFFFFF" valign="top"></td>
  </tr>
  
  <tr>
    <td bgcolor="#FFFFFF">&nbsp;</td>
    <td bgcolor="#FFFFFF">&nbsp;</td>
    <td bgcolor="#FFFFFF">&nbsp;</td>
  </tr>

</table>

</body>

</apex:page>

APEX Class
public with sharing class AccountSearchUI{    

    public ApexPages.StandardController stdController {get; set;}
    public Account acc {get; set;}
    public Account accPList {get; set;}
    
    public String accountName ='';
    public AccountSearchUI(ApexPages.StandardController stdController){
    this.stdController = stdController;

 accPList = [select Group_Org__c, Vertical__c, Name, Type, Client_Rank__c from Account where Top_25_Client__c = true and Client_Rank__c < 26 order by Client_Rank__c ASC limit 5];
    }
}
Can anyone help with the issue.
 
This is my code
=============
global class BatchApex implements Database.Batchable<sobject>{
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('select id from Opportunity');
        
    }
    global void execute(Database.BatchableContext bc,List<Opportunity>scope){
        for(Opportunity o:scope){
            o.Name='sandhya';
        }
    update scope;
}
    global void finish(Database.BatchableContext bc){
            
   Messaging.SingleEmailMessage[] mail=new Messaging.SingleEmailMessage();
        String[] toAddresses=new String[] {'forcesfdcloud@gmail.com'};
            mail.setToAddresses(toAddresses);
        mail.setSubject('sending mail ');
        mail.setPlainTextBody('process completed success fully');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
      
    }
    }
I want to update my opportunities. After updating the opportunities i want to send a mail to the above mentioned address, but it shows error like" Illegal assignment from Messaging.SingleEmailMessage to List<Messaging.SingleEmailMessage>" can any one tell me how to solve this issue.
trigger CheckValidationonCaseClose on Case (after update) {     
for(Case e:Trigger.New){          
Case d=Trigger.oldMap.get(e.Id);         
if(d.Signature_Required__c==true && d.Customer_Signature_Status__c!='Completed' && e.IsClosed==true)
{  
e.adderror('Cannot Close Case');
}

its urgent
}  
Hi,

I have a rquirement to format a time which is given in HH:MM format (24-hour clock) into the user's locale. I assumed that there would be a fromat() method as the DateTime class does, but it does not exist.

Any ideas how I can do this?

Thanks
I have a Salesforce App which passed security review for the first time in the last year. This App also includes integration with external web application, due to this I also submitted a BURP scan report of the external web application. I am not sure about how Salesforce conducts periodic security review and have some queries.

As you may know, Salesforce provides periodic, point-in-time review at an interval determined by salesforce.com (typically anywhere between 6 months to 2 years).

• As per Salesforce documentation for already passed Apps, around the expiry date, Salesforce contacts partners to arrange another review. Can you guide me on how much time Salesforce gives us to prepare for Security Review?

• BURP scan and fixing the issues reported by it can take time. If I could not submit a clean BURP scan report within the time frame provided by Salesforce, Does Salesforce remove package from AppExchange?

• Salesforce charges for Security Review process for paid Apps, as one-time upfront fee, and a small subsequent annual fee. Can you guide me on how much subsequent annual fee Salesforce charges to partners? Salesforce also charges annual listing fee of $150 USD. Is that correct?

Kindly help me with this. Thanks in advance.
Hi All,

I want to disable the global search for particular users,i have disabled the chatter in chatte section,please give me suggestion how to disable the global search.
see the below screen shot where i have disabled
User-added image

see the below screen shot for what i want to disable 

User-added image

Thanks,
Surya
I'm stuck on only one unit for this module; the controlling access to fields unit:

"Two team members need to view and update Accounts, but only one should be able to see and edit the Rating field. Create one profile and one permission set with field level security to solve for this use case.The profile must be named 'Basic Account User' and result in an API name of 'Basic_Account_User'. It should use the 'Salesforce' user license type.
The permission set must be named ‘Account Rating’ and result in an API name of 'Account_Rating'."

"Challenge Not yet complete... here's what's wrong:
The 'Basic Account User' profile did not have the appropriate object and field-level security for the Account object "
  • February 02, 2016
  • Like
  • 1
Hi Jacob,

I have already completed 5 badges, but still no email for obtaining the Cloak of Adventure sweatshirt. Does it take username or email address for sending emails, as my email address and user name are different.

User-added image
Hi,

I want to send an email alert to task owner if they have any open task which due date is already passed.
I want to send it 1 day after due date and 1 week after due date.
Please suggest how I can achieve it because through workflow it is not achievable.

Regards
Emily
 view state and need a steps how can we reduce view state without help of transient
Hi,

I have executed "Run all test" to get code coverage of all apex classes. Is there way to get all apex classes code coverage with percentage copy to excel sheet. I am able to see all classes with percentage in Developer console. But not able to copy all those. Please provide some suggestion.
We are using Apex Data Loader 19.0 and cliq_process.  Using Apex Data Loader & Cliq_process, we are exporting the data into salesforce custom object. The process was working fine past 2 years and till last week. Last few days we are getting the below error.


2015-08-17 06:12:31,218 INFO  [ExportRevenue] process.ProcessRunner run (ProcessRunner.java:104) - Logging in to: https://www.salesforce.com/services/Soap/u/19.0
2015-08-17 06:12:31,233 INFO  [ExportRevenue] client.PartnerClient login (PartnerClient.java:989) - Beginning Partner Salesforce login ....
2015-08-17 06:12:31,249 INFO  [ExportRevenue] client.PartnerClient login (PartnerClient.java:998) - Salesforce login to https://www.salesforce.com/services/Soap/u/19.0/services/Soap/u/19.0 as user forceuser@<company>.com
2015-08-17 06:12:31,655 INFO  [ExportRevenue] dao.DataAccessObjectFactory getDaoInstance (DataAccessObjectFactory.java:51) - Instantiating data access object: C:\Program Files\salesforce.com\Apex Data Loader 19.0\cliq_process\ExportRevenue\write\ExportRevenue.csv of type: csvWrite
2015-08-17 06:12:31,655 INFO  [ExportRevenue] process.ProcessRunner run (ProcessRunner.java:109) - Checking the data access object connection
2015-08-17 06:12:31,655 INFO  [ExportRevenue] process.ProcessRunner run (ProcessRunner.java:114) - Setting field types
2015-08-17 06:12:31,766 ERROR [ExportRevenue] client.PartnerClient describeSObject (PartnerClient.java:1249) - Error while calling web service operation: describeSObject, error was: Failed to send request to https://ncst.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
com.sforce.ws.ConnectionException: Failed to send request to https://<company>.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:113)
    at com.sforce.soap.partner.PartnerConnection.describeSObject(PartnerConnection.java:48)
    at com.salesforce.dataloader.client.PartnerClient.describeSObject(PartnerClient.java:1240)
    at com.salesforce.dataloader.client.PartnerClient.setFieldTypes(PartnerClient.java:1196)
    at com.salesforce.dataloader.controller.Controller.setFieldTypes(Controller.java:127)
    at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:115)
    at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:229)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:847)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:402)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:170)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:836)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
    at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:97)
    at com.sforce.ws.transport.JdkHttpTransport.connect(JdkHttpTransport.java:82)
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:99)
    ... 6 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
    at sun.security.validator.Validator.validate(Validator.java:203)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)
    at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:840)
    ... 19 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:236)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:194)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:216)
    ... 24 more
2015-08-17 06:12:31,766 FATAL [main] process.ProcessRunner topLevelError (ProcessRunner.java:214) - Unable to run process ExportRevenue
java.lang.RuntimeException: com.sforce.ws.ConnectionException: Failed to send request to https://<company>.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
    at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:139)
    at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:229)
Caused by: com.sforce.ws.ConnectionException: Failed to send request to https://<company>.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:113)
    at com.sforce.soap.partner.PartnerConnection.describeSObject(PartnerConnection.java:48)
    at com.salesforce.dataloader.client.PartnerClient.describeSObject(PartnerClient.java:1240)
    at com.salesforce.dataloader.client.PartnerClient.setFieldTypes(PartnerClient.java:1196)
    at com.salesforce.dataloader.controller.Controller.setFieldTypes(Controller.java:127)
    at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:115)
    ... 1 more
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:847)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:402)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:170)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:836)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
    at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:97)
    at com.sforce.ws.transport.JdkHttpTransport.connect(JdkHttpTransport.java:82)
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:99)
    ... 6 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
Exact replication steps:
1. Create a connected app
2. Add the callback URL to that connected app as the URL of a VF page. For Eg - 'https://c.eu2.visual.force.com/apex/mypage'.
3. Connect to another salesforce org of the same instance.Énter the login details ie username and password
4. Allow permission to the connected app create on your source org to access info about target org by clicking on Állow Button'
5. Instead of redirecting back to source org it redirects me to the target org and tries to open up the page mentioned in the callback url.
6. This issue is coming when my source and target org are on same instance. It works fine when source and target instances are different.
Hello,
I have some queries on release versioning and listing subsequent versions on AppExchange:
  1. Can I release and maintain 2 versions on AppExchange? In other words, if there a v1.0 that is listed on AppExchange, and we release a new version v1.1 that has passed Security Review and ready to be listed on AppExchange, does it automatically replace the v1.0 that was listed earlier? 
  2. Do the existing customer orgs get any notification of a new released version? If yes, does it automatically contain the install link? If not, what is the most preferred practice?
  3. If I deprecate an earlier version, do the customer orgs using this version get a notification to upgrade? Are they forced to upgrade?
  4. If a patch is created for a particular released version, do I have to manually inform all customer orgs using it? Or do they get automatic notifications of the same and can choose to apply the patch as needed?
Thanks in advance!
Hi,

I want to develop an "Open CTI Adapter", where can I find the documentation(API/Library) for the same?

Regards,
Rohan
Hi ,
  
 I'm trying to parse Account records to JSON string. But I'm getting unnecessary data like attributes(type,url) that is not required in String.

Can any one pls help me in how to parse the string to required format.
List<Account> accnts=[Select Name,Phone From Account];
String s=JSON.serialize(accnts);
The resulting output is in below fromat..
{
  "attributes" : {
    "type" : "Account",
    "url" : "/services/data/v34.0/sobjects/Account/00128000002trGGAAY"
  },
  "Name" : "GenePoint",
  "Phone" : "(650) 867-3450",
  "Id" : "00128000002trGGAAY"
}


My requirement is to generate resulting String as below JSON string format.
 
{
  "Name" : "GenePoint",
  "Phone" : "(650) 867-3450",
  "Id" : "00128000002trGGAAY"
}

So that I can minimize the data to to be sent the the client system.

Any help is really appreciated. Thanks in advance.

Regards,
Naveen.
I need to download Contacts Near By component for the trailhead - field sales app project but I am not able to find it on appexchange. Any idea where can I get it from?