You need to sign in to do that
Don't have an account?
*****ApexCode bug????******
Dears
After read and change my class acording to this manual http://wiki.developerforce.com/index.php/An_Introduction_to_Apex_Code_Test_Methods I got 74% of coverage of my code, second issue after change my class with these three method I cannot complete the request, I got this error "Callout from triggers are currently not supported.: Class.APICallV2.invokeWebService: line 44, column 28" my class has @future (callout=true), is important to note that the last class (http://boards.developerforce.com/t5/Apex-Code-Development/Test-API-Call-Future-callout-true/td-p/207766) work perfect in sandbox but is not posible to test and migrate to production (link with the class and advise http://boards.developerforce.com/t5/Apex-Code-Development/Test-API-Call-Future-callout-true/td-p/207766) below the code for your advise:
trigger Event_Trigger on Event( after insert, before update) {//verificar funcionamiento de future call con update before
/*
si cambia a.RecordTypeId el nombre o el ID del campo de debe cambiar en cada if el codigo anterior (012A0000000Bg6CIAS)
*/
System.debug('Making future call');
for (Event a : Trigger.new) {
if (Trigger.isInsert) {
if(a.RecordTypeId != '012A0000000Bg6CIAS'){//only for recordtype Masivo, this value (012A0000000Bg6CIAS) can not change
/*******getting info for below procedures***************/
List<Account> l = [Select Account.latitud__c, Account.Categoria__c From Account Where Id=:a.WhatId];
string latitud = l[0].latitud__c ;
string tipo_cliente = l[0].Categoria__c ;
string Categoria = l[0].Categoria__c ;
if(latitud == null){// if latitude is not completed the user need to go to account and set the latitude and longitude values
a.addError(' No es posible crear la visita, por favor dirigase al módulo de Cliente y agrega las latitud y longitud de la dirección utilizando el mapa. ');
}
string contact_preson = a.WhatId;//contact ID for Rest API
string Id_event = a.Id; //ID of event for REST API
Datetime inicio = a.StartDateTime; //Date of start meeting
Datetime fin = a.EndDateTime; //Date of end meeting
/*****Section to check is the meeting is point for the same month.****/
date startDate = date.today();
date dueDate = date.newInstance(inicio.year(),inicio.month(),inicio.day());
integer numberMonthsDue = startDate.monthsBetween(dueDate);
integer tot;
if(numberMonthsDue == 0 ){
integer c = [SELECT count() FROM Event where OwnerId=:a.OwnerId and WhatId=:a.WhatId and StartDateTime = THIS_MONTH];
tot = c;
}
if(numberMonthsDue > 0 ){
integer c = [SELECT count() FROM Event where OwnerId=:a.OwnerId and WhatId=:a.WhatId and StartDateTime = NEXT_MONTH];
tot = c;
}
//section visit per type of client
if(tipo_cliente == 'Uno (1)'){//cada 15 dias
if(tot > 2){//menor a dos visitas mensiales
a.addError(' No es posible crear mas de 2 visitas por mes para este cliente, en caso de no poder asistir a visitas previamente programadas para este mes, por favor ingrese nuevamente a esa visita y reprograme. ' );
//+tot+' '+Categoria+' lat '+latitud+' what id '+a.WhatId+' whot id '+a.WhoId
}
}
if(tipo_cliente == 'Dos (2)'){//cada 30 dias
if(tot > 4){//menor a tres visitas mensiales
a.addError(' No es posible crear mas de 4 visitas por mes para este cliente, en caso de no poder asistir a visitas previamente programadas para este mes, por favor ingrese nuevamente a esa visita y reprograme. '+tot);
}
}
if(tipo_cliente == 'Cuatro (4)'){//cada semana
if(tot > 8){//menor a cinco visitas mensuales
a.addError(' No es posible crear mas de 8 visitas por mes para este cliente, en caso de no poder asistir a visitas previamente programadas para este mes, por favor ingrese nuevamente a esa visita y reprograme. '+tot);
}
}
//END section visit per type of client
//send te data future method
Http h = new Http();
APICallV2 v = new APICallV2();
HttpRequest req = v.buildWebServiceRequest();
v.invokeWebService(h, req,inicio,fin,Id_event,contact_preson );
}//si no es negocio (recordtype)
}//isinsert
}//trigger new
for (Event a : Trigger.new) {
if (Trigger.isUpdate) {//para update
if(a.RecordTypeId != '012A0000000Bg6CIAS'){//only for recordtype Masivo, this value (012A0000000Bg6CIAS) can not change
if(a.Fecha_inicio_real__c == null && a.Fecha_Hora_fin_real__c ==null && !a.Efectividad_de_la_visita__c){
/*******getting info for below procedures***************/
List<event> e = [Select Event.StartDateTime From Event Where Id=:a.Id];
// Datetime Date_Start_old = datetime.now() ;
// Datetime Date_Start_new = datetime.now();
Datetime Date_Start_old = e[0].StartDateTime ;
Datetime Date_Start_new = a.StartDateTime;
string contact_preson = a.WhatId;//contact ID for Rest API
string Id_event = a.Id; //ID of event for REST API
Datetime inicio = a.StartDateTime; //Date of start meeting
Datetime fin = a.EndDateTime; //Date of end meeting
/*****Section to reschedule forthe same month.****/
Date Date_Start_new_date = date.newInstance(Date_Start_new.year(), Date_Start_new.month(), Date_Start_new.day());//se pasa a formato date
Date Date_Start_old_date = date.newInstance(Date_Start_old.year(), Date_Start_old.month(), Date_Start_old.day());//se pasa a formato date
integer numberDaysDue =Date_Start_old_date.daysBetween(Date_Start_new_date);
integer numberMonthsDue =Date_Start_old_date.monthsBetween(Date_Start_new_date);
if( numberMonthsDue > 0){//msj de error
a.addError(' Usted dede reprogramar su la visita en el mes en curso.');
}// > 10
Http h = new Http();
APICallV2 v = new APICallV2();
HttpRequest req = v.buildWebServiceRequest();
v.invokeWebService(h, req,inicio,fin,Id_event,contact_preson );
}
}//si no es negocio recordtype.
}//isbefore
}//trigger old
}//principal
Continue below........
Could you please clarify if this error represent a bug in salesforce?
cond part......
/**************************************************************class*****************************/
public class APICallV2{
//Future annotation to mark the method as async.
@future (callout=true)
public static void APICallV2_request(){
/*
object w
Http h = new Http();
w.invokeWebService(h, req, fecha_inicio, fecha_fin, Event_Id, account_Id);
*/
}
public HttpRequest buildWebServiceRequest(){
HttpRequest req = new HttpRequest();
req.setEndpoint('https://apisphere.locationsmart.com/restapi/v_1_1/sphere');
req.setMethod('POST');
return req;
}
public HttpResponse invokeWebService(Http h, HttpRequest req,Datetime fecha_inicio, Datetime fecha_fin, string Event_Id, string account_Id){
//Invoke Web Service
List<account> b = [Select latitud__c, Longitud__c From Account Where Id=:account_Id];
string latitud = b[0].latitud__c;
string Longitud = b[0].Longitud__c;
Datetime fecha_fin_def = fecha_fin.AddHours(1);//time dif our time -4:30 GMT (time difference with your servers and salesforce)
Datetime fecha_inic_def = fecha_inicio.AddHours(-1);//time dif -4:30 GMT (time difference with your servers and salesforce)
req.setBody( '<request> <authentication> <username>333</username> <password>dd</password> </authentication> <sphere> <name>'+Event_Id+'</name> <campaign>ccc</campaign> <onEnter> <processId>495320073</processId> <processPayload><payload><value>'+Event_Id+'</value></payload></processPayload> </onEnter> <onExit> <processId>333</processId> <processPayload><payload><value>'+Event_Id+'</value></payload></processPayload> </onExit> <device>333</device> <zone> <address>'+Longitud+' '+latitud+'</address> <radius>90</radius> <unitType>mtrs</unitType> </zone> <startDate>'+fecha_inic_def+' +0000</startDate> <endDate>'+fecha_fin_def+' -0000</endDate> </sphere></request>');
// Create a new http object to send the request object
// A response object is generated as a result of the request
Http http = new Http();
HTTPResponse res = http.send(req);
req.setMethod('POST');
return res;
}
public void handleWebServiceResponse(HttpResponse res){
//Parse and apply logic to the res message
if (res.getStatusCode() == 200) {
System.debug('Exitoso '+ res);
} else {
System.debug('Callout failed: ' + res);
}
}
}//class
/************************************** test clkass************************************/
@isTest
private class TestAPICallV2
{
//Added for security review
static testMethod void testWebService(){
Http h = new Http();
APICallV2 v = new APICallV2();
//First, build the http request
HttpRequest req = v.buildWebServiceRequest();
Datetime fecha_inicio = datetime.now();
Datetime fecha_fin = datetime.now();
string Event_Id ='00UA00000041osdMAA';
string account_Id ='001A000000LKjdeIAD';
//NOTE - WE DO NOT EXECUTE THE METHOD, invokeWebService.
v.invokeWebService(h, req,fecha_inicio, fecha_fin, Event_Id, account_Id);
//Now, since we can't execute the actual web service,
//write apex code to build a sample HttpResponse object
HttpResponse res = new HttpResponse();
//Apply test data and attributes to the HttpResponse object as needed
v.handleWebServiceResponse(res);
}
}//Test class
Could you please clarify if this error represent a bug in salesforce?
Hi everyone I will like to update this case, after try and read the error I found that the test stop when arrive the the line
v.invokeWebService(h, req,fecha_inicio, fecha_fin, Event_Id, account_Id); so I move it to the last section of my class and the test coverage increase to 84%.
The second issue is not solved yet "Callout from triggers are currently not supported.: Class.APICallV2.invokeWebService: line 44, column 28".
Waiting for feedback.