• andy81
  • NEWBIE
  • 56 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 13
    Replies
I have created a class which helps to automatically update a geolocation field. I have also given the test class but the code coverage is only 72%. below is the code and test class. The lines of code which is in bold are not covered by the test class. Can anyone help with writing test class.

public class AccountGeocodeAddress{
// static variable to determine if geocoding has already occurred
private static Boolean geocodingCalled = false;
// wrapper method to prevent calling future methods from an existing future context
public static void DoAddressGeocode(id
accountId) {
  if
(geocodingCalled || System.isFuture()) {
    System.debug(LoggingLevel.WARN, '***Address Geocoding Future Method Already Called - Aborting...');
    return;
  }
  // if not being called from future context, geocode the address
  geocodingCalled = true;
  geocodeAddress(accountId);
}
// we need a future method to call Google Geocoding API from Salesforce
@future (callout=true)
static private void geocodeAddress(id accountId)

  // Key for Google Maps Geocoding API
  String geocodingKey = 'AIzaSyAYPyw3l--jV92bEfgq20vfAggygvqiIPg';
  // get the passed in address
  Account geoAccount = [SELECT BillingStreet, BillingCity, BillingState, BillingCountry, BillingPostalCode FROM Account WHERE id = :accountId];
    
  //check that we have enough information to geocode the address
  if((geoAccount.BillingStreet == null) || (geoAccount.BillingCity == null)) {
    System.debug(LoggingLevel.WARN, 'Insufficient Data to Geocode Address');
    return;
  }
  //create a string for the address to pass to Google Geocoding API
  String geoAddress = '';
  if(geoAccount.BillingStreet != null)
    geoAddress += geoAccount.BillingStreet + ', ';
  if(geoAccount.BillingCity != null)
    geoAddress += geoAccount.BillingCity + ', ';
  if(geoAccount.BillingState != null)
    geoAddress += geoAccount.BillingState + ', ';
  if(geoAccount.BillingCountry != null)
    geoAddress += geoAccount.BillingCountry + ', ';
  if(geoAccount.BillingPostalCode != null)
    geoAddress += geoAccount.BillingPostalCode;
  
  //encode the string so we can pass it as part of URL
  geoAddress = EncodingUtil.urlEncode(geoAddress, 'UTF-8');
  //build and make the callout to the Geocoding API
  Http http = new Http();
  HttpRequest request = new HttpRequest();
  request.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?address=' + geoAddress + '&key=' + geocodingKey + '&sensor=false');
  request.setMethod('GET');
  request.setTimeout(60000);
  try {
    //make the http callout
    HttpResponse response = http.send(request);
    //parse JSON to extract co-ordinates
    JSONParser responseParser = JSON.createParser(response.getBody());
    //initialize co-ordinates
    double latitude = null;
    double longitude = null;
    while(responseParser.nextToken() != null) {
      if((responseParser.getCurrentToken() == JSONToken.FIELD_NAME) && (responseParser.getText() == 'location')) {
        responseParser.nextToken();
        while(responseParser.nextToken() != JSONToken.END_OBJECT) {
         
        String locationText = responseParser.getText();
         
        responseParser.nextToken();
         
        if (locationText == 'lat')
           
        latitude = responseParser.getDoubleValue();
         
        else if (locationText == 'lng')
           
        longitude = responseParser.getDoubleValue();
        }
      }
    }
    //update co-ordinates on address if we get them back
    if(latitude != null) {
      geoAccount.Location__Latitude__s = latitude;
      geoAccount.Location__Longitude__s = longitude;
      update geoAccount;
    }

  } catch
(Exception e) {
    System.debug(LoggingLevel.ERROR, 'Error Geocoding Address - ' + e.getMessage());
  }
}
}

Test Class

@IsTest 
public class KioskGeocodeAddressTest {
    Static testMethod void testkioskGeocodeAdress(){
        FuseBox_Kiosk_Address__c kiosk = new FuseBox_Kiosk_Address__c(Name = 'Test');
        kiosk.Street_Name__c = '4500 Truxel rd';
        kiosk.Address_Line_2__c = 'Apt 1015';
        kiosk.City__c = 'Sacramento';
        Kiosk.State__c = 'California';
        Kiosk.Zip_Code__c = '95833';
        kiosk.Country__c = 'United States';
        insert kiosk;
        test.startTest();
        string status;
        HttpRequest request = new HttpRequest();
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('GoogleMapsAPI');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'application/json');
        mock.respond(request);
        HttpResponse response = new HttpResponse();
        JSONParser responseParser = JSON.createParser(response.getBody());
        String Loc = responseParser.getText();
        double latitude = 33.33333;
        double longitude;
        // Set the mock callout mode
        Test.setMock(HttpCalloutMock.class, mock);
                 
        // Call the method that performs the callout
        kioskGeocodeAddress.DoAddressGeocode(kiosk.Id);
        system.assertNotEquals(latitude,kiosk.Location__Latitude__s);
    }
}
Hello Experts, I need to create the attached look and feel for senior management review reporting. I am using visualforce page and am able to create most of it using Apex - however, I need your help on how can I create two pageblocksection on the same row - see Update on Relationship & Voice of Customer in the attached?


User-added image
This trigger simply prevents a user from inserting a record on an object.  It's not bulkified since the whole point is to prevent any record from being inserted at all.   It works fine but I wanted to check with the community to see if anyone sees anything wrong with the code or if it might be improved:
 
trigger FeedItemTrigger on FeedItem(Before Insert){

    /*Ross Gilbert 6/9/2015: The following prevents a Salesforce user from inserting any new Feed Item object in Salesforce*/
 
    for(FeedItem fi: trigger.new){
        fi.addError('Chatter is not currently supported for Salesforce.  You are not allowed to create new chatter posts or comments at this time.');
    }
}
What do you think?
 
I'm trying to show all the errors in my VisualForce page using my own styling, so I include <apex:messages> at the top of the page (instead of <apex:pageMessages>) and add the appropriate styleClass attribute. It's working fine (was guided by http://salesforce.stackexchange.com/questions/8139/difference-between-the-multiple-messaging-options-in-visualforce).

Now I have a requirement to include a hyperlink in an error message itself, yet the 'escape='false'" attribute available in <apex:pageMessages> is not available in <apex:messages>.

Do I really have to choose between Salesforce styling with the ability to hyperlink an error message, my own styling without that ability, or rolling my own error messaging from scratch? Hoping I'm missing something.

Thanks for any ideas!
I am unable to resolve my test class. Before including trigger.oldmap it was 80% coverage. Now it is 0%. Any suggestions could be helpful for me.

Thank you.

Trigger:
trigger populateOpportunityfromContact on Opportunity (before insert , before update)
{
    
    Set<ID> ConIds = new Set<ID>();

    for(Opportunity opp : trigger.new)
    {
          ConIds.add(opp.RSM_Shipping_Contact__c);    
    }

    list <contact> conlist = [SELECT Email,Id,MailingCity,MailingCountry,MailingPostalCode,MailingState,MailingStreet,Phone FROM Contact where id IN:ConIds];

     MAP<ID , contact> mapCon = new MAP<ID , Contact>();
     for(Contact c : conlist)
     {
        mapcon.put(c.id,c);
     }

     for(Opportunity opp : trigger.new)
     {
      if(trigger.oldmap.get(opp.Id).RSM_Shipping_Contact__c != opp.RSM_Shipping_Contact__c)
      {

        if(opp.RSM_Shipping_Contact__c!=null)
        {
        if(mapcon.containskey(opp.RSM_Shipping_Contact__c))
        {
          contact c = mapcon.get(opp.RSM_Shipping_Contact__c);
          opp.Shipping_Street__c = c.MailingStreet;
          opp.Shipping_City__c = c.MailingCity;
          opp.Shipping_State__c = c.MailingState;
          opp.Shipping_Country__c= c.MailingCountry;
          opp.Shipping_postal_code__c = c.MailingPostalCode;
          opp.Shipping_Email__c = c.Email;
          opp.Shipping_Phone__c = c.phone;
        }
       
        }
        
        else
        {
            
          opp.Shipping_Street__c = null;
          opp.Shipping_City__c = null;
          opp.Shipping_State__c = null;
          opp.Shipping_Country__c= null;
          opp.Shipping_postal_code__c = null;
          opp.Shipping_Email__c = null;
          opp.Shipping_Phone__c = null;
            
        }
       
     }
    }
        
}

Test Class:
 
@istest

public class populateOpportunityfromContactTestclass
{
     @testSetup static void setup() 
      {
                
        contact c = new contact();
        c.lastname = 'Gopi Jayaram';
        c.mailingstreet = '1409 Roper Mountain Road';
        c.mailingcity = 'Greenville';
        c.mailingstate = 'South Carolina';
        c.mailingcountry = 'United State of America';
        c.mailingpostalcode = '29615';
        c.email = 'gopijayaram@gmail.com';
        c.phone = '4053786543';
        insert c;
        
        
        opportunity o = new opportunity();
        o.name = 'Gopi Jayaram ATT';
        o.RSM_Shipping_Contact__c = c.id;
        o.stagename = 'prospecting';
        o.closedate = Date.today();
        insert o;

     }
     
     Static testMethod void insertItemNull()
     {
         Opportunity op = [Select id, name,Shipping_Street__c from opportunity where name = 'Gopi Jayaram ATT' ];
        // contact ct = [Select id,email,phone,mailingstreet,mailingcity,mailingstate,mailingcountry,mailingpostalcode from contact where name = 'Gopi Jayaram' ];
         System.assertnotequals(op.Shipping_Street__c,null);
     } 
      Static testMethod void insertItem()
     {
         Opportunity op = [Select id, name,Shipping_Street__c from opportunity where name = 'Gopi Jayaram ATT' ];
        contact ct = [Select id,email,phone,mailingstreet,mailingcity,mailingstate,mailingcountry,mailingpostalcode from contact where name = 'Gopi Jayaram' ];
         System.assertequals(op.Shipping_Street__c,ct.mailingstreet);
     } 
     
}

 
Hey guys, I am stuck on this formula, maybe you can help...I am trying to say, if the close date is not blank and if the close date is this month, then return MRR.

Check it out:
IF(AND(NOT(ISBLANK(CloseDate)),CloseDate=MONTH(today())),MRR__c , null)

I am getting this error "Error: Incorrect parameter type for operator '='. Expected Date, received Number"
.
I am unsure on how to show a date for "this month". Any ideas?
Create a Visualforce page that uses a custom controller to display a list of cases with the status of 'New'.The page must be named 'NewCaseList'.
The custom controller Apex class must be named 'NewCaseListController'.
The 'NewCaseListController' Apex class must have a publically scoped method named 'getNewCases'.
The 'getNewCases' Apex method should have the return type of 'List' and return a list of case records with the ID and CaseNumber fields and filtered to only have a status of 'New'.
The 'NewCaseList' Visualforce page must use an apex:repeat component which is bound to 'newCases'.
The apex:repeat component must refer to the var attribute as 'case'.
Within the apex:repeat component, bind a apex:outputLink component to the ID of the case so that the page directs the user to the detail page of the respective case record
I'm pretty new to development, and have modified code found elswhere on the internet.  The code is working find in my sandbox, but when i attempt to deploy it to production, there's no test classes and so it fails.

Here's the code:

// Use a name besides "lead" otherwise you'll get compilation problems due to symbol collision
public with sharing class leadApexZipCode {
    
    private static boolean isTrigger = false;        // Pitfall #4: Used to prevent infinite loops
    public class leadException extends Exception {}

    /* format from ziptasticapi.com:  
        {"country":"US","state":"CA","city":"SAN JOSE"}
    */
    // Format returned by ziptastic API
    public class ziptasticReturn {
        string country;
        string state;
        string city;
    }    
     
    // Trigger Handler to do zipCodeLookup when new records are created
    //  Do this after the record is created so we have an ID we can reference
    public static void onAfterInsert( List<lead> triggerNew)
    {
        // Pitfall #4 - Prevent infinite loops
        if (isTrigger == true) {
            return;                // Just return if this is called as a result of our DML operation
        } else
           isTrigger = true;    // Set this so we know we caused ourselves to be called again
        
        // Must pass IDs & not SObjects to @future because the SObject may change by the time @future executes
        List<Id> leadsId = new List<Id>();
        for (lead a : triggerNew) {
            leadsId.add(a.Id);
        }    
        system.debug(LoggingLevel.Info, 'onAfterInsert called with '+triggerNew+'; sending IDs='+leadsId);
        makeZipCallout(leadsId);
    }
    
    // Pitfall #1 & #2 - Triggers must do callouts from an '@future' and (callout = true) anotated function
    @future (callout = true) 
    private static void makeZipCallout(List<Id>acct)
    {
        system.debug(LoggingLevel.Info, 'makeZipCallout with '+acct);
        string resp;
        
        // Pitfall #3 - Fetch records of the IDs for updating
        List<lead> leadSet = [SELECT Id, Postalcode, City, State, Country
                                    FROM lead 
                                    WHERE Id = :acct];
        
        for (lead a : leadSet) {
            
            // Note this version of the API is only for the US
            string endpoint ='http://ziptasticapi.com/';
            endpoint = endpoint + a.Postalcode;
            system.debug(LoggingLevel.Info,'zipCode.cls: calling endpoint='+endpoint);
     
            HttpRequest req = new HttpRequest();
            HttpResponse res = new HttpResponse();
            Http http = new Http();
            req.setMethod('GET');
            req.setEndpoint(endpoint);
     
            try {
              res = http.send(req);
              if (res.getStatusCode() != 200) {
                throw new leadException(res.getStatus());
              }
            } catch (leadException e) {
              system.debug(LoggingLevel.Error, 'Error HTTP response code = '+res.getStatusCode()+'; calling '+endpoint );
              return;
            }
      
            resp = res.getBody();
            JSONParser parser = JSON.createParser(resp);
            parser.nextToken(); // Start object "{"
        
            ziptasticReturn zipInfo = new ziptasticReturn();
            // This convenient method reads the JSON stream into a class in one go
            zipInfo = (ziptasticReturn) parser.readValueAs(ziptasticReturn.class);
            a.State = zipInfo.state;
            a.City = zipInfo.city;
            a.Country = zipInfo.country;
            
        }    
        update leadSet;        // Call DML operation to update
        isTrigger = false;        // Pitfall #4 - Trigger is done so reset this
    }        // makeZipCallout()

}
Hi,
I have a trigger and a class which implements a queueable interface.
When a record gets created the trigger invokes the queueable interface which will make a callout.

Now I'm writing the test class for the same.
In the test class I'm setting the mock response using httpMockCallout and inserting the record.
But I'm getting an exception, Callout loop not allowed.
Any Idea why this is happening?

As a workaround I set the response using test.Isrunningtest and it works fine.

Any pointers would be helpful.
Many Thanks
Dear 

I need assistane. I dont know more what i can do, show me "Arithmetic expressions must use numeric arguments at line 13 column 29"


public class FrequenciaCompra{
    public static void Frequencia(Account[] Conta) {
        for (Account b :Conta){
            AggregateResult[]  opp =
                [SELECT accountid,count(CloseDate) n
                FROM Opportunity
                WHERE 
                CloseDate>=:b.Primeira_Oportunidade__c and
                CloseDate<=:b.Ultima_Oportunidade__c and
                accountid=:b.id
                group by accountid] ;
            date startDate=b.Ultima_Oportunidade__c;
            b.Frequencia__C=startDate.daysBetween(b.Primeira_Oportunidade__c)/opp[0].get('n');
            b.update;
        }
    }
    
}