• tonante
  • NEWBIE
  • 169 Points
  • Member since 2012
  • Salesforce Developer

  • Chatter
    Feed
  • 4
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 26
    Questions
  • 53
    Replies
I tried 3 different ways of deleting the classes from Production. First I tried using change sets and then the Eclipse force.com IDE. Now the ANT migration tool. Everytime I try to remove the class I'm getting this error. Please help!!

remove:
[sf:deploy] Request for a deploy submitted successfully.
[sf:deploy] Request ID for the current deploy task: 0Af3700000InZRSCA3
[sf:deploy] Waiting for server to finish processing the request...
[sf:deploy] Request Status: InProgress
[sf:deploy] Request Status: InProgress (12/14)  -- Running Test: TestTriggerCustomObjectUpdate.testBulkUpdate
[sf:deploy] -----------------------------------------------------------------------------------
[sf:deploy] Test Failures:
[sf:deploy] 1.  TestTriggerCustomObjectUpdate.TestReferralUpdate -- System.Exception: Assertion Failed: Expected: null, Actual: 00137000009XLFjAAO
[sf:deploy]     Stack trace: Class.TestTriggerCustomObjectUpdate.TestReferralUpdate: line 26, column 1
[sf:deploy] -----------------------------------------------------------------------------------
[sf:deploy] Request Status: Failed

BUILD FAILED
C:\Users\rramachandra\Desktop\salesforce_ant_35.0\ant-demo\build.xml:35:
*********** DEPLOYMENT FAILED ***********
Request ID: 0Af3700000InZRSCA3

All Test Failures:
1.  TestTriggerCustomObjectUpdate.TestReferralUpdate -- System.Exception: Assertion Failed: Expected: null, Actual: 00137000009XLFjAAO
    Stack trace: Class.TestTriggerCustomObjectUpdate.TestReferralUpdate: line 26, column 1
2.  TestTriggerCustomObjectUpdate.testBulkUpdate -- System.Exception: Assertion Failed: Expected: null, Actual: 00137000009XLFkAAO
    Stack trace: Class.TestTriggerCustomObjectUpdate.testBulkUpdate: line 75, column 1

Code Coverage Failures:
1.  Class: chatter_answers_question_escalation_to_case_trigger -- Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required
2.  Average test coverage across all Apex Classes and Triggers is 65%, at least 75% test coverage is required.
*********** DEPLOYMENT FAILED ***********

Is there a way to force delete? I'm new to salesforce and I have no idea about these terms "tests coverage" or even how/where to write a test on my own.
Can anyone explain to me the difference between a Process Builder that contains Scheduled Actions to call a flow versus a Process Builder that used Wait Elements  within the flow for its immediate action?

I was contemplating using Process Builder that would call a scheduled action to create 3 tasks some 90 days after a certain date but I never got that scheduler to call the flow action. However when I used Wait Element for this 90-day delay (by setting the Wait Element  Offset Number to just 1 day)  it called the flow after the conditon was satisfied. Maybe I'm misunderstanding their respective uses. Thanks
HI:
I have created a Process Builder whose object is set to fire when an Account object is created or updated. I created a condirion on the Account's Planned Start Date and then I set the Scheduled Actions to 90 days after the Planned Start Date and I have added an action to create a couple of tasks. The problem is that when this process builder fires none of the interviews actually wait. I verified this by looking at the debug logs. The interviews just flow through from begind and end and there are no flows in the Pause and Waiting Interviews buffer. I have attached a screenscrape.  Thanks
.Scheduled Actions Not being Paused.
HI 
 I have found out how to programatically  auto-follow individual users who are account owners and I have feed tracking set on two fields for the user's account records

Q) Is there a way to filter on certain  field values  for these 2 fields which will be tracked and posted to  that user's Chatter so as not to display/post certain feeds if a field value doesn't meet some criteria?     (User doesn;t car about every value for a field)  Thanks
HI,
In the assingment I am given I not only have to set feed tracking on certain account fields but I must  display those filed changes based on certain field values. (I think you can do this for Cases but no other object)  For example:
If I am tracking on Registration_Status__c file, I don't want the Feed Item to post this record change if the field value  = 'Renew".  However, I want the Feed Item to post this record change when the field value is either "Reinstated", "New" or "Dropped".  I have searched other areas of Salesforce and can't find any info on this. Thanks for any help or suggestions you could give me.   
HI, we have a private chatter group based on Account Feed Tracking with a few members added. However we would like to be able to make any Account  records posted to the group invisible to all members except the Account Owner.

Is there any way to do this?   (I have the triggers doing feed posts to the group already with FeedItem object. I just need to direct them to the Account Owner only).

 Thanks much for any advice or suggestions.
HI: I just wanted to solicit comments or ideas  concerning this issue:
We need to  programmatically keep the Opportunity Team Members and Send an email to the new account owner instead of doing it manually. So we'd use a trigger.

I know there is an idea out on the Success Community which is up for votes on how to handle this but has not reached the vote limit to pass yet:
https://success.salesforce.com/ideaView?id=08730000000cGUJAA2

However can't we just do these following procedural steps in Apex? Please let me know your ideas or comments because I really want to know if this makes any sense before I code it. Thanks much for your help:

If account owner is changing:
  1. Select each Opportunity Team Member (OTM) object using the Opportunity's Account Id
  2. Delete the old Account Team Member (ATM) Role of Sales Director
  3. Store the OTM object in a list of OTMs
  4. Insert the new Account Owner as the ATM's new Sales Director.
  5. Upsert the OTM list.
  6. Send email to the new Account Owner.
 I am assuming that once the Owner has been changed and has been Addeed as the new Sales Director in the Account Team, that these Oppotunity Team Member objects will not be kept when opportunities are transfered to the new owner if I don;t do those steps.

 
  • September 21, 2016
  • Like
  • 0
HI

 Q) SInce the KB article below indicates that  setting the Email Bounce Back feature will not work on workflows   and that there is no way to track email alerts that are sent to an invalid email address from a work flow does anyone know of an alternative or workaround to solve this problem?  See the KB article here:

https://help.salesforce.com/apex/HTViewSolution?urlname=Workflow-Rule-Email-Alert-Does-Not-Utilize-Bounce-Management-Address

Thanks
  • September 15, 2016
  • Like
  • 0

HI I need help. I have a SOQL Query that has a checbox field  - Authorized_Purchaser__c - as on of  its attribute and wanted to check the value of this field in an IF condition statement but it seems that the value of the check box field is always true even when it is  unchecked(!?). I put debug statements on the  check box and it displays that it is true. However, after looking at it in the Affiliation object Detail Page,  I have seen that it is unchecked and thus should be false . Here is a portion of the code in question and checkbox field Authorized_Purchaser__c is the field I am trying to verify which is unchecked.  Thus it should be false however the value is set to true so the pricebook will never be added to the list of Price books. What am I missing?  Thanks much for your help.
boolean isAuthorized = true;
 
List<npe5__Affiliation__c> aff = [Select npe5__Organization__r.Registration_Level__c,Authorized_Purchaser__c,npe5__Organization__r.Name from npe5__Affiliation__c where npe5__Contact__c =: ContactId and npe5__Organization__r.Id =: AffID limit 1 ];
 
isAuthorized = aff[0].Authorized_Purchaser__c;
 system.debug('<< IS AUTHORIZED? >>> '+aff[0]);
 
for( PriceBook2 PriceBook : [SELECT Id, Name FROM PriceBook2 Where isActive = true and Name in ('Employee Price Book','Contractor Price Book')    Order By Name DESC ]){ 
    if(isAuthorized ==false && PriceBook.Name == 'Employee Price Book'){
            CompanyPriceBooks.add(PriceBook);
    }
}

 
  • September 01, 2016
  • Like
  • 0
HI we need your help:
we are using affiliation objects for a call out and we know that we can only make 10 aynchronous calls at a time  to Demandware service so we used mod 10 to handle this which worked well in other instances but here we are getting "Too many future calls:1 " . Here is the code where
ControllerToUpdateDWREAffiliation.getAccessToken(affIds) is the future method containing the affiliation list of 17 records. Thanks much.
List<String> affIds = new List<String>();
  List<npe5__Affiliation__c> affiliationList = new List<npe5__Affiliation__c>();
  User demandwareAppUser = [select Id from User where Name = 'Demandware'];
    if(Trigger.isUpdate){
        system.debug('--------------------'+demandwareAppUser.Id);
        for(npe5__Affiliation__c affiliation: Trigger.new){
            if(affiliation.LastModifiedById != demandwareAppUser.Id){
                system.debug('Affiliation Details'+'--'+'--'+affiliation.LastModifiedById);
                affiliationList.add(affiliation);
            }
        }
    }
   system.debug('*************Affiliation Size :'+affiliationList.size()); 
    
      Boolean affiliateHasChanged = false;
    for(Integer count = 0; count < affiliationList.size() ; count++){
        if(trigger.new[count].affiliationBatchFlag__c == 'updated'){
           extraAffs++;
           AccountHelper ah = new AccountHelper(trigger.new[count].Id);
                affIds.add(JSON.serialize(ah));  

             system.debug('----------**********************--------'+trigger.new[count].Id+'--'+trigger.new[count].npe5__Status__c+'--'+trigger.new[count].Mozo_User_Level__c+'--'+trigger.new[count].affiliationBatchFlag__c);
             
                if(math.mod(extraAffs,10) == 0)
                {                     
                    ControllerToUpdateDWREAffiliation.getAccessToken(affIds);
                    affIds.clear();
                }//batch ids
        }  
        
        if(trigger.old[count].npe5__Status__c != trigger.new[count].npe5__Status__c || 
           trigger.old[count].Mozo_User_Level__c != trigger.new[count].Mozo_User_Level__c){
           extraAffs++;
           affiliateHasChanged = true;
            system.debug('----------**********************--------'+trigger.new[count].Id+'--'+trigger.new[count].npe5__Status__c+'--'+trigger.new[count].Mozo_User_Level__c);
            //if(!system.isbatch()){
                AccountHelper ah = new AccountHelper(trigger.new[count].Id);
                affIds.add(JSON.serialize(ah));  
                 // TW: The following IF condition gets the even nnumber count of Ids on INSERT. This is neededdue to the @future call outs to Google. 
             
                if(math.mod(extraAffs,10) == 0)
                {                     
                    ControllerToUpdateDWREAffiliation.getAccessToken(affIds);
                    affIds.clear();
                }//batch ids
                
            //}
        }
        
    }
   
    
        if(math.mod(extraAffs ,10) != 0){ 
            ControllerToUpdateDWREAffiliation.getAccessToken(affIds);
            affIds.clear();
        }//other than batch


 
HI I am running a batch class that sets a field on account objects based on a condition and then it loads the account into a list of accounts to be bulk updated. However there is a trigger which fires on Account After Update that interrupts the Bacth job when it tries to do the DML_BEGIN (Update). That trigger takes over and attempts to process the accounts and send the info to Demandware service using a  supporting Controller Class that calls a Future Method. Thus this Batch job indirectly calls Future method so I get an exception. We need the batch job to reset the field and update the account and then we want the rest controller having the future method be able to pass this info to the Demandware server account. Thanks for your help.

1) Batch Job class:
global class BatchCancelMozoFreeTrialObject  implements Database.Batchable<sObject> {
// global variables	
	global String query;
	global class UtilException extends Exception {} 
	
	global database.querylocator start(Database.BatchableContext BC)
	{
		// Select All Accounts that have Current as their free trail Status
		if(query == null) 
		{
			query 
				= 'Select Id, '
				+ ' Mozo_Trial_End_Date__c, ' 
				+ '	Mozo_Trial_Status__c '
				+ 'From Account WHERE Mozo_Trial_Status__c = \'Current\' '
				+ ' And (RecordType.Name like \'%Church%\' Or RecordType.Name like \'%Organization%\')';
		}
		system.debug('<< QUERY  >> '+query);	
		return Database.getQueryLocator(query);
	}
 	
	global void execute(Database.BatchableContext BC, List<sObject> scope)
	{
		
		List<Account> accountsToUpdate = new List<Account>();
		List<ID> storeContactIDs = new List<ID>();
		for(sObject s : scope)
		{
			Account thisAccount = (Account)s;
			system.debug('<<DEBUG STATUS >> '+thisAccount.Id+' <<ID>> '+thisAccount.Mozo_Trial_Status__c+'<<  DATE  >> '+thisAccount.Mozo_Trial_End_Date__c+' VS  '+system.today());
			if(thisAccount.Mozo_Trial_End_Date__c <= system.today() && thisAccount.Mozo_Trial_Status__c == 'Current') { 		 
				thisAccount.Mozo_Trial_Status__c = 'Former';
				accountsToUpdate.add(thisAccount);
			}
			  
		}
		
		system.debug(accountsToUpdate);
		if(accountsToUpdate.size() > 0){
			update accountsToUpdate;
		}
	}

	global void finish(Database.BatchableContext BC)
	{

	}

}
2) Trigger which called Controller Method:
trigger updateMozoTrialToDWREAccount on Account (after update) {
    
    List<String> accountIds = new List<String>();
    List<Account> accountList = new List<Account>();
    String doNotCallController = 'success';
    RecordType rec = [select Id from RecordType where Name  = 'US Organization' limit 1];
    User demandwareAppUser = [select Id from User where Name = 'Demandware'];
    if(Trigger.isUpdate){
        system.debug('--------------------'+demandwareAppUser.Id);
        for(Account accs: Trigger.new){
            if(accs.RecordTypeId == rec.Id && accs.LastModifiedById != demandwareAppUser.Id){
                system.debug('Account Details'+'--'+accs.Name+'--'+accs.RecordTypeId+'--'+accs.LastModifiedById);
                accountList.add(accs);
            }
        }
    }
    for(Integer count = 0; count < accountList.size() ; count++){
        if(trigger.old[count].Mozo_Trial_Status__c != trigger.new[count].Mozo_Trial_Status__c || 
           trigger.old[count].Mozo_Free_Trial_ContactID__c != trigger.new[count].Mozo_Free_Trial_ContactID__c ||
           trigger.old[count].Mozo_Trial_Start_Date__c != trigger.new[count].Mozo_Trial_Start_Date__c ||
           trigger.old[count].Mozo_Trial_End_Date__c != trigger.new[count].Mozo_Trial_End_Date__c){
            
            system.debug('--'+trigger.new[count].Id+'--'+trigger.new[count].Mozo_Free_Trial_ContactID__c+'--'+trigger.new[count].Mozo_Trial_Status__c+'--'+trigger.new[count].Mozo_Trial_Start_Date__c+'--'+trigger.new[count].Mozo_Trial_End_Date__c);
            //DemandwareController.getAccessToken(trigger.new[count].Id,trigger.new[count].Mozo_Free_Trial_ContactID__c,trigger.new[count].Mozo_Trial_Status__c,trigger.new[count].Mozo_Trial_Start_Date__c,trigger.new[count].Mozo_Trial_End_Date__c);
            
            if( trigger.old[count].Mozo_Trial_Status__c == 'Former' && trigger.old[count].Mozo_Trial_End_Date__c == trigger.new[count].Mozo_Trial_End_Date__c && (trigger.new[count].LastModifiedById == '00550000000vuyG' || trigger.new[count].LastModifiedById == '00550000001qiyX')){
                doNotCallController = 'fail';
            }
            if(doNotCallController == 'success'){
                AccountHelper ah = new AccountHelper(trigger.new[count].Id);
                accountIds.add(JSON.serialize(ah));  
                ControllerToUpdateDWREAccount.getAccessToken(accountIds);
            }
        }
    }
    
}
3. Controller used by Trigger that has the Future method:
Global class ControllerToUpdateDWREAccount {
    @future (callout=true)
    
      global static void getAccessToken(List<String> accountIds){
    //system.debug(accId+' '+MozoTContactId+' '+MozoTStatus+' '+MozoTStartDate+' '+MozoTEndDate);
        String accErrorId;
        AccountHelper currIds = null;
        List<Account> accList = new List<Account>();
        //String exceptionString = 'MethodNot';
        try{
            string accToken='';
            Http http = new Http(); 
            HttpRequest req = new HttpRequest();
            HttpRequest req1 = new HttpRequest();
            HttpRequest reqUpdate = new HttpRequest(); 
            
            for (String ser : accountIds)
           {
            
             currIDs = (AccountHelper) JSON.deserialize(ser, AccountHelper.class);
             System.debug('Deserialized in future:'+currIds.Id);     
             accErrorId = currIds.Id;
             Account a = [SELECT Id,Mozo_Free_Trial_ContactID__c,Mozo_Trial_Status__c,Mozo_Trial_Start_Date__c,Mozo_Trial_End_Date__c FROM Account WHERE id =: currIds.Id];
                                
            req.setMethod('POST');
            req.setHeader('Authorization','Basic NjQ3NTMxYTktNzZmYy00ZDNhLThjYTMtNmNlNDA5ZmYxMTcxOjcvWFItQSptYWQsRUpNQE5LZD5s');
            //req.setHeader('Authorization','Basic 923d2a4c-b33b-4e3c-ad0a-370afbd46abb');
            
            req.setHeader('Content-Type','application/x-www-form-urlencoded');  
            req.setEndpoint('https://account.demandware.com/dw/oauth2/access_token?grant_type=client_credentials'); 
            
                HTTPResponse res = http.send(req); 
                JSONParser parser = JSON.createParser(res.getBody());
                while (parser.nextToken() != null) {
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getCurrentName() == 'access_token')) {
                        parser.nextToken();
                        accToken = parser.getText();    
                    }
                }      
                system.debug('-----Demandware Access Token-------'+ accToken);
                if(accToken != null || accToken != ''){
                    req1.setMethod('GET');
                    req1.setHeader('Authorization','Bearer ' + accToken);
                    //req1.setEndpoint('https://staging-web-awana.demandware.net/s/-/dw/data/v16_3/custom_objects/Account/0015000000GUZYzAAP');
                    req1.setEndpoint('https://staging.store.awana.org/s/-/dw/data/v16_3/custom_objects/Account/'+a.Id);
                  
                    HTTPResponse res1 = http.send(req1); 
                    system.debug('*******************'+res1.getBody());
                    string[] headerkeys = res1.getHeaderKeys();
                    string headerValue;
                    for(string s : headerkeys){
                        if(s == 'Etag'){
                            headerValue = res1.getHeader(s);
                            system.debug('header: ' + s + ' value: ' + headerValue);
                        }
                    }
                    if(headerValue != '' || headerValue != null){
                        
                        reqUpdate.setHeader('Authorization','Bearer ' + accToken);
                        reqUpdate.setHeader('Content-Type','application/json; charset=UTF-8');
                        reqUpdate.setHeader('If-Match',headerValue);
                        Map<String,object> jsonObject = new Map<String,object>();
                        //jsonObject.put('c_MozoTrialStatus','Current');
                        jsonObject.put('c_MozoTrialStatus', a.Mozo_Trial_Status__c);
                        jsonObject.put('c_MozoTrialContactID', a.Mozo_Free_Trial_ContactID__c);
                        Integer d = a.Mozo_Trial_Start_Date__c.day();
                        Integer mo = a.Mozo_Trial_Start_Date__c.month();
                        Integer yr = a.Mozo_Trial_Start_Date__c.year();
                        
                        DateTime ST = DateTime.newInstance(yr, mo, d, 12, 0, 0);
                        jsonObject.put('c_MozoTrialStartDate', ST);
                        
                        Integer ed = a.Mozo_Trial_End_Date__c.day();
                        Integer emo = a.Mozo_Trial_End_Date__c.month();
                        Integer eyr = a.Mozo_Trial_End_Date__c.year();
                        
                        DateTime ET = DateTime.newInstance(eyr, emo, ed, 12, 0, 0);
                        
                        jsonObject.put('c_MozoTrialEndDate', ET);
                        String JSONString = JSON.serialize(jsonObject);   
                        reqUpdate.setBody(JSONString);
                        system.debug(JSONString);
                        reqUpdate.setEndpoint('https://staging.store.awana.org/s/-/dw/data/v16_3/custom_objects/Account/'+a.Id);  
                        
                        reqUpdate.setMethod('POST');
                        reqUpdate.setHeader('x-dw-http-method-override','PATCH');
   
                        
                            HTTPResponse resUpdate = http.send(reqUpdate); 
                            system.debug('*******************'+resUpdate.getBody());
                            
                    }
                }   
           }//for   
        }//try outer
       catch(Exception ne){
            system.debug('Exception '+ne);
            Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {'shaikbaji.a@ecgroup-intl.com'};
            mail.setToAddresses(toAddresses);
            mail.setReplyTo('shaikbaji.a@ecgroup-intl.com');
            mail.setSenderDisplayName('Salesforce');
            mail.setSubject('Update Failed');
            mail.setPlainTextBody('Account Id: '+accErrorId+' not existed in Demandware');
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            accErrorId = null;
        }
    }
}



 
HI,
I have an assignment to create in-line Visualforce page in order to have that display in the Acocunt Detail Page but while this is great for desktop, we need to somehow make this displayable in SF1 for mobile. I was told that Related Lists were the best way to go in order to display the information we need but sadly, we can't use custom SOQL-like filtering on rleated lists yet.

Q) Is the only solution to:
Create a custom object that will be used in a master-detail relationship with the master/StandardController object as its parent. (That's because  each related list object points back to the master/StandardController object with that master object's ID and can therefore be used as a related list)?

I was thinking that this would be the best way so far  because you could remove the task of creating pages and controller classes by creating this custom object. The way to load the filtered records into the custom object would be to do this:

Example: Load all  Advancement Opportunities  (a specific opportunity basedon recpord type) into a Custom Advancement Opportunity object (653 records in Sandbox) which has an AccountID field. Every time a new Advancement Opportunity record is created a trigger  (set to fire on Opportunity After Insert)  would fire to load the desired  data fields from the that Advancement  Opportunity into the Custom Advancement Opportunity object. Somewhat wasteful just to get a filtered related list but there seems to be no other way in SFDC b ut at least it would show up OK in SF1 mobile.  Thanks for any suggestions.


 
HI , when testing batch class , may test doesn;t seem to be invoking the executeBatch() method even though it does have a valid list of opportunities for the scope. I traced the code flow in debug log to where it finished the start method in creating the QueryLocator and saw that it did contain a list of opportunities but it did not reach the executeBatch method but skipped ahead to the finish method. So now I am  only able to cover 53%.  I wonder why the Query Locator skipped to Finish upon return? Doesn;t it flow into executeBatch if the object for scope is not empty?  Here is my class code for batch: 
global class BatchGeneratePickTicketsByQuery implements Database.Batchable<sObject>
{
    global String Query;

    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String DefaultQuery = 
            ' Select Id, AccountId, Account.Name, RecordTypeId, RecordType.Name, Name, ' + 
            ' StageName, Amount, CreatedDate, CreatedById, CreatedBy.Name, HasOpportunityLineItem, LastModifiedDate, ' +
            ' LastModifiedById, LastModifiedBy.Name, TotalOpportunityQuantity, Total_Pick_Quantity__c, ' +
            ' Total_Pick_Tickets__c, Inventory_Items__c, Non_inventory_Items__c, Error_Log__c, ' +
            ' (Select Id, Name From Pick_Tickets__r) ' + 
            ' FROM Opportunity Where CreatedDate > 2012-07-01T00:00:00.000Z ' +
            ' And RecordType.Name = \'Orders\' ' + 
            ' And Amount > 0 ' + 
            ' And (StageName = \'Order Confirmed\' OR StageName like \'%Partially%\') ' + 
            ' And (NOT StageName like \'%Cancelled%\') ' + 
            ' And Id Not In (Select Opportunity__c From Sales_Order__c) ';
    
        if(Query == null) {
           Query = DefaultQuery; 
        }
        else {
            system.debug('<<QUERY>> '+Query);
            if(!Query.toLowerCase().contains('from opportunity')) { Query = null; } 
        }
        
        system.debug('QUERY >> '+Query);
        
        return Database.getQueryLocator(Query);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope)
    {
        for(sObject s : scope)
        {
            Opportunity o = (Opportunity)s;
            OrderEntryStatus.QueueGeneratePickTicket(o.Id);
        }
    }
    
    global void finish(Database.BatchableContext BC)
    {
        system.debug(BC);
    }
}
 2) Here is the Test Class for the batch class:
 
@isTest
public class BatchGeneratePickTicketsByQuery_Test {
	static testmethod void test() {
String Query =
      ' Select Id, AccountId, Account.Name, RecordTypeId, RecordType.Name, Name, ' + 
          ' StageName, Amount, CreatedDate, CreatedById, CreatedBy.Name, HasOpportunityLineItem, LastModifiedDate, ' +
          ' LastModifiedById, LastModifiedBy.Name, TotalOpportunityQuantity, Total_Pick_Quantity__c, Company__c,Shipping_Weight__c, ' +
          ' Total_Pick_Tickets__c, Inventory_Items__c, Non_inventory_Items__c, Error_Log__c ' + 
          ' FROM Opportunity Where CreatedDate > 2012-07-01T00:00:00.000Z ' +
          ' And RecordType.Name = \'Orders\' ' + 
      ' And Amount >= 0 ' + 
      ' And (Total_Pick_Tickets__c > 0 OR Pick_Ticket_Not_Fulfillable__c = true) ' + 
      ' And StageName != \'Order Cancelled\' ' + 
      ' And StageName != \'Order Invoiced\' ' + 
      ' And (Not StageName like \'%Fulfilled%\') ' + 
      ' And (StageName like \'%Partially%\' OR StageName = \'Order Confirmed\' OR Pick_Ticket_Not_Fulfillable__c = true) ' + 
      ' And Id Not In (Select Opportunity__c From Sales_Order__c)';
		
		Test.startTest();	
        BatchGeneratePickTicketsByQuery bgptbq = new BatchGeneratePickTicketsByQuery();
        bgptbq.Query= null;
        ID batchprocessid = Database.executeBatch(bgptbq);
		Test.stopTest();
    }
}

Thanks  for your help.

 
  • September 05, 2015
  • Like
  • 0
Hi, I get this error but the difference is that my SOQL queries actually return a value. I make sure they are  of size limit 1 or no greater than 4 in the ones which were flagged as errors. I have not deployed code in nearly 1.5 months , at 78% code coverage, and just last Thursday our SFDC Admin was attempting to deploy workflows using change sets and suddenly got 25 of these "Non-selective query" errors. None of the 25 errors have SQOL queries that  return Null because the queries use no variables  in the WHERE clause. Here is a sample of the SOQL code issues I am having: The "Non-Selective query" error occurs at the last query within this code segment. 
@isTest (seeAllData=true)
public class TestOpportunityAfterUpdate {
	public static testmethod void TestAdvocacyShipCharge(){
		AdvocacySupplyShipCharge_Test.TestAdvocacySupplyShipCharge();
	}
   public static testmethod void TestMozoAccounts(){
      List<Opportunity> Orders = new List<Opportunity>();
      Set<Id> contactIds = new Set<Id>();
      List<Id> orgIds = new List<Id>();
      User ouser = [SELECT Id from User where Name = 'Awana Applications' limit 1];
      RecordType rec = [Select Id from RecordType where SObjectType = 'Opportunity' and Name = 'Orders'];  
      Map<Id,Opportunity> mozoMap = new Map<Id,Opportunity>(); 
     
      List<Account> accts=[Select Id, Default_Shipping_Address__c,   Mailing_Address_Book__c,Registration_Level__c, Registration_Status__c, Date_Inactive__c,ShippingStreet,ShippingCity,ShippingState,ShippingPostalCode,ShippingCountry 
                from Account WHERE RecordType.Name = 'US Organization' and Date_Inactive__c <> null and Account_On_Hold__c = false and RecordType.Name in ('Canada Church','US Organization')  limit 4];
    
     system.debug('<< ACCOUNTS>> '+accts);   
     
     for(Account acct : accts){
       orgIds.add(acct.Id);
     }

Here is the Production Workbench Query Result from the last query of the code above. Thanks much for your help.:
Non-Selective Query error on valid queries that return valid row sets of only 4.
Hi,  If I define a global variable within  the global batch class that implements Batchable and then I update that variable in the global execute method. Why do the values for this global variable become null or empty when I try to use the variable in the global Finish method? The global variable in my case is a and object defined as List<Id> expireSoonList
and when I add values to this List of Ids and add a system debug file after the update - to show the size of this list - in method Execute , I get a non-zero value.
But when I check on the size of this list - by adding system.debug -  in the Finish method,  the global ID List is empty so I get a 0 shown for the system debug instruction . Here's the code snippet   Thanks much:
global class BatchMozoSubscriptionRenewObject implements Database.Batchable<sObject> {
    // global variables
	global List<Id> expireSoonList;
    global String query;
   global List<Id> Temp = new List<Id>();
    
    global String[] finishSubscriberEmailList;
    // Not a sandbox exception definition
	global class NotSandboxException extends Exception {} 
    
    
    global database.querylocator start(Database.BatchableContext BC)
    {
        if(query == null) 
        {
            query = 
                'Select Id, RecordType.Name, Status__c, ' 
                + 'Date_Inactive__c, Registration_Level__c ' 
                + 'From Account '
                + 'Where ( Status__c = \'Added\' and RecordType.Name in (\'Canada Church\' , \'US Organization\') ) ' 
           		+ 'And Registration_Level__c <> \'R0\' And Registration_Level__c <> null and Date_Inactive__c >= today';
        }
        
        system.debug('<<QUERY STRING>> '+query);
        
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<sObject> scope)
    {
        
       	Integer currentMonth= 0;
        Integer expirationMonth = 0;
		Integer difference  = 0;
        date currentDate = date.today();
        for(sObject s : scope)
        {	           
            Account a = (Account)s;
            expirationMonth = (a.Date_Inactive__c).month();
            currentMonth = currentDate.month();
            system.debug('<<Expire Date>> '+a.Date_Inactive__c+' <<Current Date>> '+currentDate);
            //daysBetween(Date) Returns the number of days between the Date that called the method 
            //If Date that calls the method occurs after the futuer Date, return value is negative.
            Integer numberOfDaysBetween = currentDate.daysBetween(a.Date_Inactive__c);
            if(numberOfDaysBetween <= 30 & numberOfDaysBetween >= 0){
                expireSoonList.add(a.Id);
                //upsert expireSoonList;
                system.debug('<< EXECUTE ---> EXPIRE SOON LIST>> '+expireSoonList.size());
            }
         /*    
            if(currentDate <= a.Date_Inactive__c){
                
                if(currentMonth <= expirationMonth){
					difference = (expirationMonth - currentMonth);                   	
                }
                else{ // e.g. expiration month = January and current month = September
               		expirationMonth =  expirationMonth + 12;
					difference = (expirationMonth - currentMonth);                    	
               	} //ELSE
                // Check to see if we within 30 days
                if(difference <= 1){
                	if(currentDate.day() >= (a.Date_Inactive__c).day()){
                    	expireSoonList.add(a.Id);
                    }
                }   
          	}//IF
		*/
            
        }//FOR LOOp
        Temp = expireSoonList;
    }//Execute
    
   global void finish(Database.BatchableContext BC)
   {	system.debug('<<EXPIRE SOON LIST>> '+Temp.size());
       if(expireSoonList.size()> 0){
        	//Get Affiliation from Accounts in order to get the Affliated Ontacts who have Awana Roles that are COmmanders or Secretaries and that have email.
         	Map<Id,npe5__Affiliation__c> getContacts = new Map<Id,npe5__Affiliation__c>([Select Id,npe5__Contact__c from npe5__Affiliation__c where npe5__Organization__c in: expireSoonList and Awana_Role__c in ('Commander','Club Secretary')]); 
     		
            //Now extract the Contact  Emails into one list and send the email
     		List<Contact> mozoContacts = [Select Email from Contact where Email <> null and Id in: getContacts.keyset()];
        	
            //Now create a list of emails to send once. 
        	String emailList = '';
     		for(Contact c: mozoContacts){
             	emailList = emailList + c.Email+'\t';
        	}
       
           	String emails = emailList.replaceAll('[\t ]*','');
            //Since Email's setToAddress uses a List we need to convert it using tabs then commans
            List<String> finishEmailList = emails.split(',');
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();        
            mail.setToAddresses(finishEmailList);
            //mail.setReplyTo('tonyw@awana.org');
            mail.setSenderDisplayName('Mozo Subscription Renewal');
       		mail.setSubject('Mozo Subscription Renewal');
            mail.setPlainTextBody('Your subscription is about to expire within 30 days.\nPlease renew your subscription as soon as possible in order to maintain your Mozo registration. Thank you.\n');
                    
           	//send bulk email
            Messaging.SendEmailResult[] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            system.debug(result);
        }
    }
}

 
Hi , recently my overall sandbox code coverage was at 75%. So:
1) I then upgraded certain test cases having low individual coverage so that they would get as close to 100% coverage for the classes the tested so now I was able to increase coverage an additioanl 3%.
 2) Howvever, when I ran a test case in my Developerment console it droppped the oevrall Sandbox organization coverage to 64% but the test passed at 88% for that class !
3) I was then able to get overall organizaton code coverage  back up to 78% for the sandbox by clicking on the link for calculating overall coverage using only My Name Space.

My quesiton is this:
Q) Is it true that  I could have  done a validation on  deployment with the class and test class without worrying about the sanbox coverage after the successful test  or should I always make sure that I click the link to re-test all those classes in my name space before deployment to production?

Q) Why should running one successful test case cause a massive drop of about 13% in my overall sandbox coverage?

Thanks  because this really frustrates me.
 
HI I just needed clarification on this solution that I made to the KB and wondered if I am understanding the action involved (semaphore?).
Before using the code in this solution I would have trigger recursion where one trigger process called a multiple number of times when it fired,  For example: trigger  Registration(  which fires when  Account is being inserted or before the acocunt is updated) would fire 10 times when Contact After Update trigger is fired once but there are 4 other triggers (i don;t have all their file names)  that fire only once.  This wastes time and uses unwanted resources. When I used the KB solution 000199485  above I noticed,  while looking at the debug log system.debug statements,  that the Registration trigger fires only once  (which is good) but the other 4 triggers don't get to run. To solve this , I set the static boolean flag -  firstRun - to true after the Trigger's IF Conditional  has been executed by making a call to isResetRun() method. Therefore when I re-fire the Contact After Update trigger , all the trigger processes fire once per trigger and no more because they got permission when the
firstRun flag was reset to true otherwise the other triggers would still see the flag as false and quickly exit.

Q) Is this the correct/intended result?  Here is a code sample of what I meant and pay special attention to the
checkRecursive.isResetRun() method call which I added to the KB solution code:
 
trigger AccountAfterUpdate on Account (after update) {  
if(checkRecursive.isFirstRun()){	// To avoid the recursion on trigger One Trigger Per Object
    Integer acctLimit = Trigger.new.size();             
    List<Account> UpdateAccountList = new List<Account>();     
    List<Account> UpdateRegLevelList = new List<Account>();     
    List<ID> acctIDs = new List<ID>();
    List<Account> clonedAccounts = new List<Account>();
    Account modifiedAccount;
    Account clonedAccount;
    List<RecordType> getPersonRecordType = [Select Id from recordType where Name = 'Individual_Person'];
    List<RecordType> getUSRecordType = [Select Id from recordType where Name = 'US Organization'];
    List<Account> OtherAccounts = new List<Account>();  //non-PMM Account tasks. 
	//1. See if its PMM value has changed for Account records.
    for(Integer aCnt = 0; aCnt < acctLimit; aCnt++){
    	//A. <<For Address Synchronization:>> // See if Address have been updated for Person Accounts
    	if(Trigger.new[aCnt].RecordTypeId == getPersonRecordType[0].Id){
            if(Trigger.new[aCnt].ShippingStreet != Trigger.old[aCnt].ShippingStreet ||
                Trigger.new[aCnt].ShippingCity != Trigger.old[aCnt].ShippingCity ||
                Trigger.new[aCnt].ShippingState != Trigger.old[aCnt].ShippingState ||
                Trigger.new[aCnt].ShippingCountry != Trigger.old[aCnt].ShippingCountry ||
                Trigger.new[aCnt].ShippingPostalCode != Trigger.old[aCnt].ShippingPostalCode ||
                Trigger.new[aCnt].BillingStreet != Trigger.old[aCnt].BillingStreet ||
                Trigger.new[aCnt].BillingCity != Trigger.old[aCnt].BillingCity ||
                Trigger.new[aCnt].BillingState != Trigger.old[aCnt].BillingState ||
                Trigger.new[aCnt].BillingCountry != Trigger.old[aCnt].BillingCountry ||
                Trigger.new[aCnt].BillingPostalCode != Trigger.old[aCnt].BillingPostalCode
                ){                    
			modifiedAccount = Trigger.new[aCnt];
                    	clonedAccount = new Account(Id=modifiedAccount.Id, Physical_Street_1__c =modifiedAccount.BillingStreet, Physical_City__c = modifiedAccount.BillingCity,
                                                Physical_Zip__c = modifiedAccount.BillingPostalCode,Physical_State__c = modifiedAccount.BillingState,
                                                PhysicalCountry__c = modifiedAccount.BillingCountry,Mailing_Street_1__c = modifiedAccount.ShippingStreet,
                                                Mailing_City__c = modifiedAccount.ShippingCity,Mailing_State_Province__c = modifiedAccount.ShippingState,
                                               Mailing_Zip_Postal_Code__c = modifiedAccount.ShippingPostalCode,Mailing_Country__c = modifiedAccount.ShippingCountry);
            
                    clonedAccounts.add(clonedAccount);
               }
          }  

        //B.<<For Team Member Manager:>> Check to see if the Owner Id has changed on US Organizations
       if(Trigger.new[aCnt].RecordTypeId == getUSRecordType[0].Id){ //11-23-2014 Added conditional using Record Type as a flag to process for US Orgs only.
        	if(Trigger.new[aCnt].OwnerId != Trigger.old[aCnt].OwnerId && (Trigger.new[aCnt].OwnerId != null && Trigger.old[aCnt].OwnerId != null) ){ // This should never happen  for Person Accounts.
          		UpdateAccountList.add(Trigger.new[aCnt]);
            	acctIDs.add(Trigger.new[aCnt].Id);
                
       		 }//IF
       }//IF
      
    }// FOR
	//2. <<For Team Member Manager:>> Displatch for processing which accounts ..
    if(UpdateAccountList.size() > 0){
        system.debug('<<TMACCTS>> '+UpdateAccountList);
        TeamMemberAccounts.handler(UpdateAccountList,acctIDs);       
    }  
  //3. <<For Address Synchronization on Person Accounts:>>
     if(clonedAccounts.size() > 0 ){
     	  update clonedAccounts;
     	  system.debug('*** New ACCOUNT ID *** '+clonedAccounts[0].Id+' *** New ACCOUNT Mailingn Address *** '+clonedAccounts[0].Mailing_Street_1__c+' *** New ACCOUNT PhysicalAddress *** '+clonedAccounts[0].Physical_Street_1__c); 
     	             
     }   
        
}// checkRecursion  
// Before leaving, give 'key' to the next available trigger to unlock critical section for  Access.

checkRecursive.isResetRun();  // <------------ KB Class Update. Free up the firstRun'key' .
}

The Class Code for the Semaphore used in the KM solution I changed slightly by adding a method called
isResetRun:
public class checkRecursive{
	
	private static boolean firstRun = true;
    public static boolean isFirstRun(){
    	if(firstRun){
      		firstRun = false;
      		return true;
    	}else{
        	return firstRun;
    	}
    }
    public static boolean isResetRun(){ // <------------ New method to free up the 'key' firstRun
    	firstRun = true;
    	return true;
    }
}// checkRecursive

Thanks for your help, comments, and questions. I just want to make sure that either I fixed the KB or if I have accidentally created any additional problems for myself . Again, with my solution  the 4 trigger processes only fire once after a contact has been updated.
 
 
HI, This may seem like an elementary question but I have not seen this explained anywhere in Sales Force docs however I may have overlooked this topic:

Q) Do inactive triggers still get calculated in an organization's overall coverage ?
I was thinkng that since their meta-xml status has changed to "Inactive" , the Apex Test Execution is somehow notified to omit the inactive trigger as part of  the overall coverage thus possibly increasing the organization's overalll code coverage percentage.

Brief Explanation/Reason for my question:
We have to maintain and scrub our list of older triggers and classes which may no longer be  needed  (not sure yet) due to changes in process or due to software upgrades like Non-Profit Starter Pack(which changes the Contact-Account Relationship regarding Contact's Account ID lookup by making this lookup field obsolete since accounts are now regarded as affiliations ).

Thanks much.
Hi,
I have been getting a few  'unable_to_lock_row' exception when I  run Apex Test Execute  in Production or Sandbox  but when I execute  the test cases individually (unit test)  they pass.. Even a few of  the managed package test cases  fail due to this error.
A few of the local test classes all lock on the same object.

Since I have different  test classes that need to use this object to test different functionality, My Question is:

Q) Is there a way to avoid this error ?
Q) Would I have to do  some sort of asynchronization on the test cases in order for the cases to wait for until he object is free? If so, how do I do this?

 Thanks
 I have just run Apex Test Execution in my production org and I am seeing a coverage of 75%!
1) We have recnetly loaded a bunch of Managed packe files like Non-Profit Starter pack etc.)  and some of those test cases failed during Apex Execution.
2) I found that we have old files that are at 0% in the org left by earlier consultants that I believe we don;t need anymore.

IN order to increase covrage should I:

1) Remove old unused classes with 0% coverage ? (Placed somehow by other consultants) Doesn;t that at least give and extra increase of 1% code coverage?

2) Compile the Managed packages before running the Apex Test Execution? (I never  compiled them  before running Apex Test Execution)

Thanks much for your help.
 
HI,
Whenever I need to save static resource files my IDE starts the build and then goes into a recursive loop until I select the resource in the Package Explorer and do the menu selection Force.com > Save To Server which causes the build to sleep (stops the build looping)  so that changes can be made to this file.  This seems to be only occuring with Static Resources.  I tested this for both VF pages and Apex classes and there doesn't seem to be an infinite/cyclical build issue with those.

Possible Culprit: Recently I had used EGit as version control for my code updates and used two successive projects to better manage the code changes  per project in Git.  I wonder if I should have just used one mamoth project folder to upload changes instead of categorizing them in sub project folders in the upstream of Git? 

Thanks much for your help.
 

 

HI I need Help with Site.Login and page redirects:

 

As I understand it, Site.login() uses startURL as a third parameter but startURL only contains paths to the Sites local pages.

 

Is there anyway that I could do a standard login using site.Login() and then have that call an external page? (i.e.. Somehow incorporate a Page redirect using the external StartURL).

 

 I am not performing another login at the external site. I just need to have the  login redirect the user to that external page. From there they can manually log in on that page.

 

 Thanks much for your help.

HI, we have a private chatter group based on Account Feed Tracking with a few members added. However we would like to be able to make any Account  records posted to the group invisible to all members except the Account Owner.

Is there any way to do this?   (I have the triggers doing feed posts to the group already with FeedItem object. I just need to direct them to the Account Owner only).

 Thanks much for any advice or suggestions.
HI

 Q) SInce the KB article below indicates that  setting the Email Bounce Back feature will not work on workflows   and that there is no way to track email alerts that are sent to an invalid email address from a work flow does anyone know of an alternative or workaround to solve this problem?  See the KB article here:

https://help.salesforce.com/apex/HTViewSolution?urlname=Workflow-Rule-Email-Alert-Does-Not-Utilize-Bounce-Management-Address

Thanks
  • September 15, 2016
  • Like
  • 0

HI I need help. I have a SOQL Query that has a checbox field  - Authorized_Purchaser__c - as on of  its attribute and wanted to check the value of this field in an IF condition statement but it seems that the value of the check box field is always true even when it is  unchecked(!?). I put debug statements on the  check box and it displays that it is true. However, after looking at it in the Affiliation object Detail Page,  I have seen that it is unchecked and thus should be false . Here is a portion of the code in question and checkbox field Authorized_Purchaser__c is the field I am trying to verify which is unchecked.  Thus it should be false however the value is set to true so the pricebook will never be added to the list of Price books. What am I missing?  Thanks much for your help.
boolean isAuthorized = true;
 
List<npe5__Affiliation__c> aff = [Select npe5__Organization__r.Registration_Level__c,Authorized_Purchaser__c,npe5__Organization__r.Name from npe5__Affiliation__c where npe5__Contact__c =: ContactId and npe5__Organization__r.Id =: AffID limit 1 ];
 
isAuthorized = aff[0].Authorized_Purchaser__c;
 system.debug('<< IS AUTHORIZED? >>> '+aff[0]);
 
for( PriceBook2 PriceBook : [SELECT Id, Name FROM PriceBook2 Where isActive = true and Name in ('Employee Price Book','Contractor Price Book')    Order By Name DESC ]){ 
    if(isAuthorized ==false && PriceBook.Name == 'Employee Price Book'){
            CompanyPriceBooks.add(PriceBook);
    }
}

 
  • September 01, 2016
  • Like
  • 0
HI we need your help:
we are using affiliation objects for a call out and we know that we can only make 10 aynchronous calls at a time  to Demandware service so we used mod 10 to handle this which worked well in other instances but here we are getting "Too many future calls:1 " . Here is the code where
ControllerToUpdateDWREAffiliation.getAccessToken(affIds) is the future method containing the affiliation list of 17 records. Thanks much.
List<String> affIds = new List<String>();
  List<npe5__Affiliation__c> affiliationList = new List<npe5__Affiliation__c>();
  User demandwareAppUser = [select Id from User where Name = 'Demandware'];
    if(Trigger.isUpdate){
        system.debug('--------------------'+demandwareAppUser.Id);
        for(npe5__Affiliation__c affiliation: Trigger.new){
            if(affiliation.LastModifiedById != demandwareAppUser.Id){
                system.debug('Affiliation Details'+'--'+'--'+affiliation.LastModifiedById);
                affiliationList.add(affiliation);
            }
        }
    }
   system.debug('*************Affiliation Size :'+affiliationList.size()); 
    
      Boolean affiliateHasChanged = false;
    for(Integer count = 0; count < affiliationList.size() ; count++){
        if(trigger.new[count].affiliationBatchFlag__c == 'updated'){
           extraAffs++;
           AccountHelper ah = new AccountHelper(trigger.new[count].Id);
                affIds.add(JSON.serialize(ah));  

             system.debug('----------**********************--------'+trigger.new[count].Id+'--'+trigger.new[count].npe5__Status__c+'--'+trigger.new[count].Mozo_User_Level__c+'--'+trigger.new[count].affiliationBatchFlag__c);
             
                if(math.mod(extraAffs,10) == 0)
                {                     
                    ControllerToUpdateDWREAffiliation.getAccessToken(affIds);
                    affIds.clear();
                }//batch ids
        }  
        
        if(trigger.old[count].npe5__Status__c != trigger.new[count].npe5__Status__c || 
           trigger.old[count].Mozo_User_Level__c != trigger.new[count].Mozo_User_Level__c){
           extraAffs++;
           affiliateHasChanged = true;
            system.debug('----------**********************--------'+trigger.new[count].Id+'--'+trigger.new[count].npe5__Status__c+'--'+trigger.new[count].Mozo_User_Level__c);
            //if(!system.isbatch()){
                AccountHelper ah = new AccountHelper(trigger.new[count].Id);
                affIds.add(JSON.serialize(ah));  
                 // TW: The following IF condition gets the even nnumber count of Ids on INSERT. This is neededdue to the @future call outs to Google. 
             
                if(math.mod(extraAffs,10) == 0)
                {                     
                    ControllerToUpdateDWREAffiliation.getAccessToken(affIds);
                    affIds.clear();
                }//batch ids
                
            //}
        }
        
    }
   
    
        if(math.mod(extraAffs ,10) != 0){ 
            ControllerToUpdateDWREAffiliation.getAccessToken(affIds);
            affIds.clear();
        }//other than batch


 
HI I am running a batch class that sets a field on account objects based on a condition and then it loads the account into a list of accounts to be bulk updated. However there is a trigger which fires on Account After Update that interrupts the Bacth job when it tries to do the DML_BEGIN (Update). That trigger takes over and attempts to process the accounts and send the info to Demandware service using a  supporting Controller Class that calls a Future Method. Thus this Batch job indirectly calls Future method so I get an exception. We need the batch job to reset the field and update the account and then we want the rest controller having the future method be able to pass this info to the Demandware server account. Thanks for your help.

1) Batch Job class:
global class BatchCancelMozoFreeTrialObject  implements Database.Batchable<sObject> {
// global variables	
	global String query;
	global class UtilException extends Exception {} 
	
	global database.querylocator start(Database.BatchableContext BC)
	{
		// Select All Accounts that have Current as their free trail Status
		if(query == null) 
		{
			query 
				= 'Select Id, '
				+ ' Mozo_Trial_End_Date__c, ' 
				+ '	Mozo_Trial_Status__c '
				+ 'From Account WHERE Mozo_Trial_Status__c = \'Current\' '
				+ ' And (RecordType.Name like \'%Church%\' Or RecordType.Name like \'%Organization%\')';
		}
		system.debug('<< QUERY  >> '+query);	
		return Database.getQueryLocator(query);
	}
 	
	global void execute(Database.BatchableContext BC, List<sObject> scope)
	{
		
		List<Account> accountsToUpdate = new List<Account>();
		List<ID> storeContactIDs = new List<ID>();
		for(sObject s : scope)
		{
			Account thisAccount = (Account)s;
			system.debug('<<DEBUG STATUS >> '+thisAccount.Id+' <<ID>> '+thisAccount.Mozo_Trial_Status__c+'<<  DATE  >> '+thisAccount.Mozo_Trial_End_Date__c+' VS  '+system.today());
			if(thisAccount.Mozo_Trial_End_Date__c <= system.today() && thisAccount.Mozo_Trial_Status__c == 'Current') { 		 
				thisAccount.Mozo_Trial_Status__c = 'Former';
				accountsToUpdate.add(thisAccount);
			}
			  
		}
		
		system.debug(accountsToUpdate);
		if(accountsToUpdate.size() > 0){
			update accountsToUpdate;
		}
	}

	global void finish(Database.BatchableContext BC)
	{

	}

}
2) Trigger which called Controller Method:
trigger updateMozoTrialToDWREAccount on Account (after update) {
    
    List<String> accountIds = new List<String>();
    List<Account> accountList = new List<Account>();
    String doNotCallController = 'success';
    RecordType rec = [select Id from RecordType where Name  = 'US Organization' limit 1];
    User demandwareAppUser = [select Id from User where Name = 'Demandware'];
    if(Trigger.isUpdate){
        system.debug('--------------------'+demandwareAppUser.Id);
        for(Account accs: Trigger.new){
            if(accs.RecordTypeId == rec.Id && accs.LastModifiedById != demandwareAppUser.Id){
                system.debug('Account Details'+'--'+accs.Name+'--'+accs.RecordTypeId+'--'+accs.LastModifiedById);
                accountList.add(accs);
            }
        }
    }
    for(Integer count = 0; count < accountList.size() ; count++){
        if(trigger.old[count].Mozo_Trial_Status__c != trigger.new[count].Mozo_Trial_Status__c || 
           trigger.old[count].Mozo_Free_Trial_ContactID__c != trigger.new[count].Mozo_Free_Trial_ContactID__c ||
           trigger.old[count].Mozo_Trial_Start_Date__c != trigger.new[count].Mozo_Trial_Start_Date__c ||
           trigger.old[count].Mozo_Trial_End_Date__c != trigger.new[count].Mozo_Trial_End_Date__c){
            
            system.debug('--'+trigger.new[count].Id+'--'+trigger.new[count].Mozo_Free_Trial_ContactID__c+'--'+trigger.new[count].Mozo_Trial_Status__c+'--'+trigger.new[count].Mozo_Trial_Start_Date__c+'--'+trigger.new[count].Mozo_Trial_End_Date__c);
            //DemandwareController.getAccessToken(trigger.new[count].Id,trigger.new[count].Mozo_Free_Trial_ContactID__c,trigger.new[count].Mozo_Trial_Status__c,trigger.new[count].Mozo_Trial_Start_Date__c,trigger.new[count].Mozo_Trial_End_Date__c);
            
            if( trigger.old[count].Mozo_Trial_Status__c == 'Former' && trigger.old[count].Mozo_Trial_End_Date__c == trigger.new[count].Mozo_Trial_End_Date__c && (trigger.new[count].LastModifiedById == '00550000000vuyG' || trigger.new[count].LastModifiedById == '00550000001qiyX')){
                doNotCallController = 'fail';
            }
            if(doNotCallController == 'success'){
                AccountHelper ah = new AccountHelper(trigger.new[count].Id);
                accountIds.add(JSON.serialize(ah));  
                ControllerToUpdateDWREAccount.getAccessToken(accountIds);
            }
        }
    }
    
}
3. Controller used by Trigger that has the Future method:
Global class ControllerToUpdateDWREAccount {
    @future (callout=true)
    
      global static void getAccessToken(List<String> accountIds){
    //system.debug(accId+' '+MozoTContactId+' '+MozoTStatus+' '+MozoTStartDate+' '+MozoTEndDate);
        String accErrorId;
        AccountHelper currIds = null;
        List<Account> accList = new List<Account>();
        //String exceptionString = 'MethodNot';
        try{
            string accToken='';
            Http http = new Http(); 
            HttpRequest req = new HttpRequest();
            HttpRequest req1 = new HttpRequest();
            HttpRequest reqUpdate = new HttpRequest(); 
            
            for (String ser : accountIds)
           {
            
             currIDs = (AccountHelper) JSON.deserialize(ser, AccountHelper.class);
             System.debug('Deserialized in future:'+currIds.Id);     
             accErrorId = currIds.Id;
             Account a = [SELECT Id,Mozo_Free_Trial_ContactID__c,Mozo_Trial_Status__c,Mozo_Trial_Start_Date__c,Mozo_Trial_End_Date__c FROM Account WHERE id =: currIds.Id];
                                
            req.setMethod('POST');
            req.setHeader('Authorization','Basic NjQ3NTMxYTktNzZmYy00ZDNhLThjYTMtNmNlNDA5ZmYxMTcxOjcvWFItQSptYWQsRUpNQE5LZD5s');
            //req.setHeader('Authorization','Basic 923d2a4c-b33b-4e3c-ad0a-370afbd46abb');
            
            req.setHeader('Content-Type','application/x-www-form-urlencoded');  
            req.setEndpoint('https://account.demandware.com/dw/oauth2/access_token?grant_type=client_credentials'); 
            
                HTTPResponse res = http.send(req); 
                JSONParser parser = JSON.createParser(res.getBody());
                while (parser.nextToken() != null) {
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getCurrentName() == 'access_token')) {
                        parser.nextToken();
                        accToken = parser.getText();    
                    }
                }      
                system.debug('-----Demandware Access Token-------'+ accToken);
                if(accToken != null || accToken != ''){
                    req1.setMethod('GET');
                    req1.setHeader('Authorization','Bearer ' + accToken);
                    //req1.setEndpoint('https://staging-web-awana.demandware.net/s/-/dw/data/v16_3/custom_objects/Account/0015000000GUZYzAAP');
                    req1.setEndpoint('https://staging.store.awana.org/s/-/dw/data/v16_3/custom_objects/Account/'+a.Id);
                  
                    HTTPResponse res1 = http.send(req1); 
                    system.debug('*******************'+res1.getBody());
                    string[] headerkeys = res1.getHeaderKeys();
                    string headerValue;
                    for(string s : headerkeys){
                        if(s == 'Etag'){
                            headerValue = res1.getHeader(s);
                            system.debug('header: ' + s + ' value: ' + headerValue);
                        }
                    }
                    if(headerValue != '' || headerValue != null){
                        
                        reqUpdate.setHeader('Authorization','Bearer ' + accToken);
                        reqUpdate.setHeader('Content-Type','application/json; charset=UTF-8');
                        reqUpdate.setHeader('If-Match',headerValue);
                        Map<String,object> jsonObject = new Map<String,object>();
                        //jsonObject.put('c_MozoTrialStatus','Current');
                        jsonObject.put('c_MozoTrialStatus', a.Mozo_Trial_Status__c);
                        jsonObject.put('c_MozoTrialContactID', a.Mozo_Free_Trial_ContactID__c);
                        Integer d = a.Mozo_Trial_Start_Date__c.day();
                        Integer mo = a.Mozo_Trial_Start_Date__c.month();
                        Integer yr = a.Mozo_Trial_Start_Date__c.year();
                        
                        DateTime ST = DateTime.newInstance(yr, mo, d, 12, 0, 0);
                        jsonObject.put('c_MozoTrialStartDate', ST);
                        
                        Integer ed = a.Mozo_Trial_End_Date__c.day();
                        Integer emo = a.Mozo_Trial_End_Date__c.month();
                        Integer eyr = a.Mozo_Trial_End_Date__c.year();
                        
                        DateTime ET = DateTime.newInstance(eyr, emo, ed, 12, 0, 0);
                        
                        jsonObject.put('c_MozoTrialEndDate', ET);
                        String JSONString = JSON.serialize(jsonObject);   
                        reqUpdate.setBody(JSONString);
                        system.debug(JSONString);
                        reqUpdate.setEndpoint('https://staging.store.awana.org/s/-/dw/data/v16_3/custom_objects/Account/'+a.Id);  
                        
                        reqUpdate.setMethod('POST');
                        reqUpdate.setHeader('x-dw-http-method-override','PATCH');
   
                        
                            HTTPResponse resUpdate = http.send(reqUpdate); 
                            system.debug('*******************'+resUpdate.getBody());
                            
                    }
                }   
           }//for   
        }//try outer
       catch(Exception ne){
            system.debug('Exception '+ne);
            Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {'shaikbaji.a@ecgroup-intl.com'};
            mail.setToAddresses(toAddresses);
            mail.setReplyTo('shaikbaji.a@ecgroup-intl.com');
            mail.setSenderDisplayName('Salesforce');
            mail.setSubject('Update Failed');
            mail.setPlainTextBody('Account Id: '+accErrorId+' not existed in Demandware');
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            accErrorId = null;
        }
    }
}



 
Hi All, 

I am trying to prevent people double booking a piece of equipment out. The user uses the custom object Booking Request to book out equipment for certain dates. 
For example Mike books equipment1 from the 22/06/2016 until 24/06/2016, then someone else wants to book the same piece of equipment from the 23/06/2016 until 25/06/2016 but should not be allowed as it is already booked.

I have created the following trigger which is working if someone enters the same start date, but how do i stop the record saving if they book in between the start and finish date? Any help greatly appreciated.

trigger DuplicateBookingTrigger on Booking_Request__c (before insert, before update) {
  for (Booking_Request__c br:Trigger.new)
  {
      List<Booking_Request__c> b=[select ID from Booking_Request__c where Equipment_Code__c=:br.Equipment_Code__c and Start_Date__c=: br.Start_Date__c and Finish_Date__c=: br.Finish_Date__c];
      if(b.size()>0)
      {
          br.adderror('The equipment selected is already booked for this date');
      }
   }
Hello

I am trying to invoke the Auth.SessionManagement.generateVerificationUrl(Auth.VerificationPolicy.HIGH_ASSURANCE, 'Custom Register', ApexPages.currentPage().getUrl())
from the test class and it fails with the error:

System.UnexpectedException: Salesforce System Error: 1978609353-24635 (-1912857534) (-1912857534)
Class.Auth.SessionManagement.generateVerificationUrl: line 54,

Calling this method from the test class fails But, executing the same code through the DEV console anonymous execution works fine! 

 
Hi,
Can you please help me out by answering these questions.
A company wants a recruiting app that models candidates and interviews; displays the total number of interviews on each candidate record; and defines security on interview records that is independent from the security on candidate records.What would a developer do to accomplish this task? 
Choose 2 answers.
A) Create a lookup relationship between the Candidate and Interview objects.
B) Create a trigger on the Interview object that updates a field on the Candidate object
C) Create a roll-up summary field on the Candidate object that counts Interview records.
D) Create a master-detail relationship between the Candidate and Interview objects.
 
Hoping the Ans as :A,B

2) In the Lightning Component framework, which resource can be used to fire events?ans: A,B
Choose 2 answers
Third-party Javascript code.
Javascript controller actions.
Visualforce controller actions.
Third-party web service code.

Hoping as Ans: A,B

3) What is a capability of formula fields? 
 
   Choose 3 answer 
 
A) Generate a link using the HIPERLINK function to a specific record in a legacy system
B) Determine if a datetime field has passed using the NOW function
C) Determine which of three different images to display using IF function
D) Return and display a field value from another object using the VLOOKUP function
E) Display the previous value for a field using the PRIORVALUE funtion

I think Ans: B,C,D

4)A developer wants to display all the available record types for a case Object. The developer also wants to display the picklist values for the Case.Status field. The Case Object and the Case.Status field are on a Custom Visualforce page.
Which action can the developer perform to get the record types and picklist values in the controller?
Choose 2 answers. 
Use Schema.PicklistEntry returned by Case.Status.getDescribe().getPicklistValues()
Use Schema.RecordTypeInfo returned by Case.sObjectType.getDescribe().getRecordTypeInfos()
Use SOQL to query Case records in the org to get all values for the Status picklist field
Use SOQL to query Case records in the org to get all the RecordType values available for Case 

I think Ans:A,B

5) A developer writes a SOQL query to find child records for a specific parent. Ans:5



 



How many levels can be returned in a single query?

A. 1
B. 7
C. 5
D. 3
 
Confused between option A and C.Please clarify these questions.

Thanks in advance for your help.


 

Can anyone suggest, how ca we delete apex class from production.

please provide step-step process to delete it from prod. through Force.com Eclipse.

  • October 29, 2010
  • Like
  • 1