• BritishBoyinDC
  • PRO
  • 2594 Points
  • Member since 2006

  • Chatter
    Feed
  • 94
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 30
    Questions
  • 577
    Replies
Hello,
 
We have a apex:map visualforce component that displays google maps with various data points on the map. With Winter 22 the maps no longer work. They are erroring out with the following error. Has anyone come across this issue or know what could be causing it? It works fine in Summer 21 release.

User-added image
In this apex class the logic is to update a custom lead field with a math.random() value.
public class leadRandomNumber {
	
	/* update lead status for leads related to the tasks */
    public static void updateRandomNumber (List<Lead> leadsFromTasks) {
    	
    	system.debug ('***** entering method leadRandomNumber.updateRandomNumber class *****');
    	
    	List<Lead> leadsToUpdate = new List<Lead>();
    	
    	List<Lead> leads = new List<Lead>([select Id, RandomNumber__c from Lead where Id IN :leadsFromTasks and Status='Attempting' and createddate = this_year and RandomNumber__c = null]);
    	system.debug('updateRandomNumber leads queried:' + leads.size());
    	// for leads related to the tasks apply a random number to the leads if they do not yet have one
    	for(lead ld: leads) {
    		if(ld.RandomNumber__c == null) {
    			Double rand = math.random();
    			ld.RandomNumber__c = rand;
    		}
    		leadsToUpdate.add(ld);
		}
		
		update leadsToUpdate;
		system.debug('updateRandomNumber leadsToUpdate: ' + leads.size());
    	
    }
    
}

This unit test verifies that inserting the task causes the logic in the apex class above to run and update the leads as expected.
 
/*
- For leads whose lead status was just updated as the result of an attempting call
- check that the random number was set
 */
 
@isTest
private class leadRandomNumberTest {

    static testMethod void insertAttemptingCall() {
    	
    	system.debug('Inserting outbound preview call tasks as a new logo rep...');
    	
    	User newLogoRep = [select id from user where isactive = true and profile.name = 'Inside Sales User' limit 1];
    	
    	QueueSobject smbQueue = [select queue.id from queuesobject where queue.name = 'SMB AE Queue'];
    	
    	Lead l = new Lead(Company='Company',LastName='Test',Phone='8885551234',Status='Open',LeadSource='Marketing', ownerid=smbQueue.queue.id);
        insert l;
        
        // bulk insert a list of calls related to the lead
        Task task = new Task(WhoId=l.Id, OwnerId=newLogoRep.Id, Type = 'Call', Five9__Five9CallType__c='Outbound Preview', Subject='Call Attempting', Status='Completed', Five9__Five9SessionId__c='fb3636336363', ActivityDate=date.today(), Five9__Five9HandleTime__c = '00:01:59', Five9__Five9WrapTime__c = '00:00:29');
        
        test.startTest();
        
        system.RunAs(newLogoRep) {
        	insert task;
        }
        
        system.debug('Asserting that the leads status was updated to Attempting and it now has a RandomNumber value...');
        
        Task insertedTask = [select Id, Status from Task where Id =: task.id];
        System.assertEquals('Completed',insertedTask.Status);
        
        // check that the lead was updated as expected
        Lead insertedLead = [select Id, Status, RandomNumber__c from Lead where Id =: l.Id];
        System.assertEquals('Attempting',insertedLead.Status);
    	System.assertNotEquals(null,insertedLead.RandomNumber__c);
    	
    	system.debug('random number set to: ' + insertedLead.RandomNumber__c);
    	
    	test.stopTest();
    
    }

}
However the test coverage for the apex class is only 56% as the updates inside the for loop are not covered.

code that needs coverage

What is the best practice for test coverage for the lines that are missing?
Hi all. My first question over here in the foreign climes of the dev boards - go easy on me, I am but a mere admin. :-)

I have written a trigger which stops an account being deleted if one of its field values is not null. This works as expected. I have written the test class, which is at 100% coverage but one of my asserts is failing. The asserts around the delete being blocked work fine - it is the negative case, where the field is null and so where the delete should go ahead, that is not working.

Here is my test class, with the delete and failing assert highlighted:
 
@IsTest
public class PreventAccountDeletionTest {

    private static testMethod void testDeleteSuccess()
    {
           Account acc=new Account(Name='Test Account');
           insert acc;
           
           System.assertNotEquals(acc.Id, null);
           System.assertEquals(acc.Some_Field__c, null);

           delete acc;
                 
           System.assertEquals(acc.IsDeleted, true);
        }

    private static testMethod void testDeleteFail()
    {
           Account acc=new Account(Name='Test Account', Some_Field__c='ABCDEFGHIJKLMNOP');
           insert acc;
  
           try
           {
              delete acc;
              // should throw an exception - the following assertion will cause an error if the code carries on
              System.assert(false);
           }
           catch (DMLException e)
           {
               // expected
               System.assert(e.getMessage().contains('You cannot delete an Account which is linked to the external system.'));
           }
        
        System.assertEquals(acc.IsDeleted, false);
        
    }

}

Any suggestions? Is there something I don't know about deleting in a test class? As the record is (hopefully) in the recycle bin do I need to use something like the equivalent of ALL ROWS? Or any other obvious thing that I'm missing?

Oh and let me know if you want to see the trigger code. Many thanks in advance!
/*
 * **Created by Jack Wang 9.24.2014
*/
global class AR_Creating75DummyNML implements Database.Batchable<sObject>{
    
    static final Integer numofNML=75;
    global final String query;
    global AR_Creating75DummyNML(String q)
    {
        query=q;
    }
    
    public List<Task> createNML(List<ID> IDs)
    {
        integer size=IDs.size();
        List<integer> ints=new List<integer>();
        
        Integer numberDays = date.daysInMonth(Date.today().year(), Date.today().month());
        for(integer i=0;i<75;i++)
        {
            double k=Math.random()*size;
            ints.add(k.intValue());          
        }
        
        
        string userid=null;
        User[] users=[select id from User where name='Jeremy Young'];
        if(users.size()>0)
        {
            userid=users[0].id;
        }
        List<Task> tsks=new List<Task>();
        for(Integer i : ints)
        {
            double datek=Math.random()*numberDays;
            Task nml=new Task(ownerid=userid,CallType__c='NML',whatid=String.valueOf(IDs[i]),Subject='NML',
                              Status='Completed',Priority='Normal',ActivityDate=Date.today().tostartofMonth().addDays(datek.intValue()));
            tsks.add(nml);
        }
        return tsks;
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC)
    {        
        return Database.getQueryLocator(query);        
    }
    
    global void execute(Database.BatchableContext BC, List<Account> scope)
    {
        
        Map<String,List<ID>> territoryClientIDMap=new Map<String,List<ID>>();
        for(Account client : scope)
        {
            if(territoryClientIDMap.containsKey(client.client_territories__c))
            {
                territoryClientIDMap.get(client.client_territories__c).add(client.Id);
            }
            else
            {
                territoryClientIDMap.put(client.client_territories__c, new List<ID>());
                territoryClientIDMap.get(client.client_territories__c).add(client.Id);
            }
        }
        
        for(List<ID> clientIDS : territoryClientIDMap.values())
        {
            List<Task> tsks=createNML(clientIDS);
            insert tsks;
        }
        
        
    }
    
    global void finish(Database.BatchableContext BC)
    {
        
    }

}
@isTest
private class Test_AR_Creating75DummyNML {
    
    
    static testMethod void Test(){
        //create 10 advisors
        ////for each advisor create 100 clients
        //

        string userid=null;
        User[] users=[select id from User where name='Jeremy Young'];
        if(users.size()>0)
        {
            userid=users[0].id;
        }
        List<Account> advisors=new List<Account>();
    
        For(integer i=0;i<10;i++)
        {
            Account a=new Account(name='a'+String.valueOf(i),client_territories__c='a'+String.valueOf(i),account_type__c='provider',Monthly_Activity_Reporting__c=true,Account_Status__c='active');
            advisors.add(a);
        }
        insert advisors;
        
        For(integer j=0;j<advisors.size();j++)
        {
            List<Account> clients=new List<Account>();
            For(integer i=0;i<100;i++)
            {
                Account client=new Account(name=advisors[j].name+String.valueOf(i),client_territories__c=advisors[j].client_territories__c,account_type__c='prospect');
                clients.add(client);
            }
            insert clients;
        }
        
        
        List<Account> advisors1= [select client_territories__c from Account where
                                (account_type__c='provider' or account_type__c='advisor') 
                                 and Monthly_Activity_Reporting__c=true and Account_Status__c='active'];
        List<String> territories=new List<String>();
        List<String> advisorIDs=new List<String>();
        for(Account advisor : advisors1)
        {
            territories.add(advisor.client_territories__c);
            advisorIDs.add(advisor.id);
        }        
        //[select id,client_territories__c from Account where client_territories__c in :territories];
        string tempquery='Select id,client_territories__c from Account where client_territories__c in (';        
        for(String terr : territories)
        {
            tempquery+='\'';
            tempquery+=terr;
            tempquery+='\',';
        }
        tempquery=tempquery.substring(0, tempquery.length()-1);
        tempquery+=') and id not in (';
        for(String adid : advisorIDs)
        {
			tempquery+='\'';
            tempquery+=adid;
            tempquery+='\'';
            tempquery+=',';
        }
        string query=tempquery.substring(0, tempquery.length()-1);
        query+=')';
        
        Test.startTest();
        AR_Creating75DummyNML c=new AR_Creating75DummyNML(query);
        Database.executeBatch(c);
        Test.stopTest();
        
        List<Task> tsk=[select ownerid,CallType__c,Subject,
                              Status,Priority,ActivityDate from Task where createddate=TODAY and CallType__c='NML'
                       and ownerid= :userid and Status='Completed' and Priority='Normal'];
        
        //75 tasks for each advisor
        System.assertEquals(750, tsk.size());
        
        
	}

}

I tried to google this error, but I didn't get a satisfied answer.


I'm having a difficult time to get my code coverage increased (I'm still a newb on the dev end).

My class is working and the test class passes, but I'm not able to piece it all together.  Any help?

 

My Class to display values on a VF page...

public class ascSummary{

    public ascSummary() {

    }


    public ascSummary(ApexPages.StandardController controller) {

    }


        public Visit__c getVisit()
    {
        
        //Retrieve Audit Results based on Id parameter of this page
        return [Select Id,
                Visit__c.Account__c,
                Visit__c.Contact__c,
                Visit__c.Visit_Date__c,
                Visit__c.Pre_audit_score__c,
                Visit__c.Workshop_Score1__c,
                Visit__c.Total_3_0v2__c,
                Visit__c.Total_4_0v2__c,
                Visit__c.Total_5_0v2__c,
                Visit__c.X1_0__c,
                Visit__c.X2_0__c,
                Visit__c.X3_0__c,
                Visit__c.X4_0__c,
                Visit__c.X5_0__c,
                Visit__c.Total_Percent__c,
                Visit__c.Total_Audit_Score__c
                from Visit__c j
                where Id = 
:ApexPages.currentPage().getParameters().get('id') ];
    }
}

 My test class..

@isTest
private class ascSummaryTestClass {
     static testMethod void validateascSummary() {
         visit__c v = new visit__c (Account__c='001c000000Qm4kp', Contact__c = '003c000000N7Bl0');
         insert v;
        
          // Retrieve the contact from the visit
        v = [SELECT Contact__c FROM Visit__c WHERE Id =:v.Id];
    System.debug('Contact after visit created: ' + v.Contact__c);  
    }
}

 

 

Hey guys,

 

I thought that the primary selling point of Force.com sites is creating public web pages where you can display data to users without requiring a login where our VF pages could be accessed by the Site guest user provided we gave the right object access to the guest user profile.

 

We want to display a custom object and its chatter feed and we need it to be read only. I thought this will be possible but it turns out that the Guest user does not have access to the Chatter APIs.

 

Has anybody else run into this problem? We are hoping to avoid having to ask the users to login.

Any thoughts on this problem would be much appreciated.

 

Thanks.

I am getting this error when I go into Edit mode for a record. I'm using the same controller & VF page that I am using for a New record of the same object. 

SObject row was retrieved via SOQL without querying the requested field: Contract_Overview__c.Contract_Start_Date__c 

 

 

I thought it would solve the problem to retrieve the field in my query  (such as Name and Contract_Type_c) - but then I just get the same error for the next field which is included as an input field in the VF page. I guess I could solve the whole problem by just retrieving EVERY single field which is an input field in the VF page, but I don't want to have to do that. There's gotta be a better way. 

 

Here is the controller being used : 

 

public class MycontrollerSFDCBETA2{

    public String rightOptionsHidden { get; set; }

    public String leftOptionsHidden { get; set; }

    public MycontrollerSFDCBETA2() {

    }

    public Account selectedUser { get; set; }
    String contractid;
    public Contract_Overview__c contract{get;set;}
    public string relatedAccount{get;set;}
    public string names{get;set;}
    public string accountid{get;set;}
    public Name contractnew{get;set;}
    public string selectedaccountid{get;set;}
    public String message { get; set; }

    public List<SelectOption> selectedContacts { get; set; }
    public List<SelectOption> options { get; set; }

    public MycontrollerSFDCBETA2(apexpages.standardcontroller controller)
        {
        selectedContacts = new list<SelectOption>();
        contract = new Contract_Overview__c();
        contractid=system.currentpagereference().getparameters().get('id');
            if(contractid!=null)
            {
                contract=[select account__c,Name,Contract_Type__c,  Subsidiaries_On_Contract__c from Contract_Overview__c  where id =:contractid];
                relatedAccount=Contract.account__C;
            }
        }

    public pageReference  execute()
        {
        accountid=contract.Account__c;
        System.debug('########'+accountid);
        return null;
        }

    public list<selectoption> getitems()
        {
        
        List<selectoption> options= new list<selectoption>();
                    
        if(accountid != null)
            {
                account a =[select name , (select name from Subsidiaries_and_Brands__r) from account where id =:accountid];
        for(SubsidiariesAndBrands__c s : a.Subsidiaries_and_Brands__r)
                    {
                    options.add(new SelectOption(s.name,s.name));
                    }
            }
        else
            options.add(new SelectOption('None','None'));
            return options;
            
        }
            
    public void save()
        {
        
        System.debug('********************************' + names);
        
        message = null ;       
        Boolean first = true;
        for ( SelectOption so : selectedContacts ) {
            if (first) {
                message = message ;
            }
            
                
            message = message + ', ' + so.getValue() ;
            
            first = false;
            
        }
        
        message=message.removeStart('null, ');
        message='['+message+']';
        
        System.debug('********************************' + message);
        contract.Subsidiaries_On_Contract__c=message;
        
        insert contract;
        contract=new Contract_Overview__c  ();
        System.debug('********************************' + contract);
                  
        }
}

 

and here's part of the VF page : 

 

<apex:outputLabel value="Contract Overview Name : "/>
                    <apex:inputfield value="{!contract.Name}" />
                    <apex:outputfield value="{!contract.OwnerId}"/>
                    <apex:outputLabel value="Contract Type : "/>
                    <apex:inputfield value="{!contract.Contract_Type__c}" required="false"/><br></br>
                    <apex:outputLabel value="Contract Status : "/>
                    <apex:inputfield value="{!contract.Contract_Status__c}" required="false"/><br></br>
                    <apex:outputLabel value="Contract Start Date : "/>
                    <apex:inputfield value="{!contract.Contract_Start_Date__c}" required="false"/><br></br>

 

 

 

So, in other words, if I retrieve Status__c in the query I'll just get that same sObject error for Contract_Start_Date__c and so on and so on...

I'm sure there's gotta be a better way than this. Anybody know them ? 

Thank you very much for your help.

 

Hey Guys

I need some help

 

I have built the following apex trigger ( See below) however i need to apply the company search on a certain records types.

The Record types in question are  “FDMS Lead Generation  &  FDMS Sales Lead”, where do i add this into the code?

My apex trigger is


Trigger DuplicateLeadPreventer on Lead

                               (before insert, before update) {

 

    Map<String, Lead> leadMap = new Map<String, Lead>();

    for (Lead lead : System.Trigger.new) {

                               

        // Make sure we don't treat an Company name that 

       // isn't changing during an update as a duplicate. 

   

  if ((lead.company != null) &&

                (System.Trigger.isInsert ||

                (lead.company !=

                    System.Trigger.oldMap.get(lead.Id).company))) {

                               

            // Make sure another new lead isn't also a duplicate 

   

            if (leadMap.containsKey(lead.company)) {

                lead.company.addError('Another new lead has the '

                                    + 'same company name.');

            } else {

                leadMap.put(lead.company , lead);

            }

       }

    }

               

    // Using a single database query, find all the leads in 

   

    // the database that have the same company address as any 

   

    // of the leads being inserted or updated. 

   

    for (Lead lead : [SELECT company FROM Lead

                      WHERE company IN :leadMap.KeySet()]) {

        Lead newLead = leadMap.get(lead.company);

        newLead.company.addError('A lead with this company '

                               + 'name already exists.');

    }

}
  

Hi,

 

 I have a small doubt,

 

1) I am building a site for a exam which is internal to the orgn , How to restrict the site based on organisation ip,

 

2) The site should to be visible only to specific ip (within orgn)

 

Please tell me how to do it

 

Thanks in advance

I want to embed javascript coding in visualforce. The javascript coding is for integrating 'Bitly' platform with salesforce.

 

My visualforce code is:

 

<apex:form >
<apex:inputText value="{!Candidate__c.Long_Url__c}" id="theText" onclick="javascript&colon;go('{!$Component.theText}')" ></apex:inputText>

  <script type="text/javascript" src="/js/functions.js"></script>
    <script src="/soap/ajax/11.1/connection.js"></script>
    
   <script language="javascript">
    
   function go(f) {
    var theText = document.getElementById(f).value;
   alert(theText);
   }
var xhr = new XMLHttpRequest(); 

xhr.open("GET", "http://api.bitly.com//v3/shorten?login=tseth&apiKey=R_948fa681da46221f969e83b2ba52d31e&longUrl="+theText);

xhr.onreadystatechange = function(){ 

alert('test');
if(xhr.readyState == 4) { 
if(xhr.status==200) { 
var jsonResponse = JSON.parse(xhr.responseText);
var bitlyUrl = jsonResponse.data.url; 

myFunc(bitlyUrl);
var t = xhr.send();
}
}
}

</script>
</apex:form>
<apex:form >
<apex:actionFunction name="myFunc" action="{!field}">
<apex:param name="param1" value=""/>
</apex:actionFunction>
</apex:form>

</apex:page>

 

Bitly is used for URL shortening. I want the shortened url to be passed to the controller through <apex:actionfunction>.

 

Please help. Its really urgent. I am completely stuck.

 

Thanks

 

 

hi I have a ApexScheduler Class which need to be test inorder to
deploy can anybody suggest me the way to achieve it to get the
coverage. I am posting the code below

 

global class ScheduleTerritoryInactiveMemberCheck implements 
Schedulable { 
    global void execute(SchedulableContext SC) { 
        TerritoryInactiveMemberCheck bcc = new 
TerritoryInactiveMemberCheck(); 
          bcc.query = 'select id,name from territory'; 
             Database.executeBatch(bcc,200); 
  }
 
} 

 cheers,

naga

 

I was wondering if someone could help a newb to SFDC come up with the code for an apex trigger.

 

Here's the scenario:

 

I have a custom object called payments (Payments__c) - a child object  of opportunities - and I would like a payment record to be created after a new opportunity record is created, but only if a checkbox is checked (Create_New_Payment__c).

 

There are a few fields on the new payment record that need to be pre-populated:

  1. The opportunity field (obviously)
  2. Payment amount (Amount__c) should equal the amount of the opportunity (the payment amount field is not a formula field and can't be, but maybe this can be accomplished with workflow - if Create_New_Payment__c is true, payment amount equals opportunity amount??)
  3. Paid__c checkbox equals true

So is this possible to do?

 

Thanks for any help.