• Sreenu Reddy 16
  • NEWBIE
  • 15 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 16
    Replies
how to solve complexity of methods directly affects maintenance costs  in class
Hi Floks....I  got some issue here . please help on this. my issues is 
System.HttpResponse[Status=Internal Server Error, StatusCode=500]
This is my code :
public class RESTExample {
  public String result{set;get;}   
  public string grant_type{set;get;}
  public string Accesstoken{set;get;} 
  public string username{set;get;}
  public string password{set;get;}
  public string client_id{set;get;}
  public string client_secret{set;get;} 
    public string getAccesstoken(){     
    String reqbody ='grant_type='+password+'&client_id='+client_id+'&client_secret='+client_Secret+'&username='+username+'&password='+password; 
        
      Http p= new Http (); 
      HttpRequest req= new HttpRequest ();
      
      req.setEndpoint('https://sandbox-us-api.experian.com/oauth2/v1/token'); 
      req.setMethod('POST');         
      req.setBody(reqbody);       
      system.debug('@@@@the reponse value is ###'+req.getbody()); 
       
       req.setHeader('Content-Type','application/json;charset=UTF-8');
       req.setHeader('accept','application/json');       
       try{ 
         HttpResponse res = p.send(req);  
         system.debug('###the reponse value is@@@ '+res.getbody()); 
         
         //system.debug('#### the value is %%%%%'+res);            
          
        
     // Map<String, String> results = (Map<String, String>) JSON.deserializeUntyped(res.getBody()); 
     // system.debug('@@@Access token value&&&'+ result);
       String accessToken ; 
       System.JSONParser parser=JSON.createParser(result);
               
             while (parser.nextToken() != null)  {
                  if ((parser.getCurrentToken() == JSONToken.FIELD_NAME))
                      {
                                            String fieldName = parser.getText();
                                            parser.nextToken();
                                            System.debug('fieldName'+fieldName);
                                            if (fieldName == 'access_token') 
                                                {
                                                accessToken = parser.getText();
                                                } 
                     }
           }
            }
         catch (Exception e){
         }  
     return accessToken;       
     }
  }
    
Challenge not yet complete in My Trailhead Playground 1
There was an unexpected error in your org which is preventing this assessment check from completing: System.CalloutException: IO Exception: Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://th-apex-soap-service.herokuapp.com/parks
sfdc flocks can you give me  help on below code .

Method does not exist or incorrect signature: void put(Decimal, String) from the type Map<Id,String> at line 8 column 24

trigger changeowner on Lead (before insert) {
     Map<Id,String> zipCodeUserMap = new Map<Id,String>();
     List<Zip_Code__c> zipCodes = new List<Zip_Code__c>();
     zipCodes = [Select id,ZipCode__c,Counserlor__c  from Zip_Code__c];
      
      for (Zip_Code__c zc :zipCodes){
        
        zipCodeUserMap.put(zc.ZipCode__c,zc.Counserlor__c);   
     }
       
       
       
       for(Lead l : Trigger.new) 
       {
        if(zipCodeUserMap.containsKey(l.Zip_Code__c)) 
        {
            l.Ownerid = zipCodeUserMap.get(l.Zip_Code__c);
        }
       }
}

hi viewers: i have two fields in task obj most recent campaign (lookup to campaign)  and description , i want to update the description  as mosot resend campaign (lookup to campaign ) in task.. using before trigger. i wrote some logic  updateDescription on Task (Before insert,Before Update) . i am getting fallowing error when i am create record. any one help me .


{

            set<id> setcmpnid =new set<id>();
            
            for(task tsk:trigger.new)
              {
                String wId = tsk.WhatId;
                
                if(wId!=null && !setcmpnid.contains(tsk.WhatId))
                { 
                  setcmpnid.add(tsk.WhatId);
                  system.debug('++++++ the setcmpnid  value is +++++++'+setcmpnid);
                } 
            }
            
            if(setcmpnid.size()>0) {
            
            list<campaign> tskcmpn= [Select id, Description from campaign where id in :setcmpnid ];
            
            Map<id,campaign> cmpn= new Map<id,campaign>();
               for(campaign cpn : tskcmpn)
              {
                  cmpn.put(cpn.Id,cpn); 
                   system.debug('++++++ the campaign id value is +++++++'+cmpn);
              }
            
              for (task tsk:trigger.new) {
                                
                String wId = tsk.WhatId; 
            
               if(wId!=null) { 
                  
               campaign thiscpn = cmpn.get(tsk.WhatId);  
               
               if(thiscpn != null){
               
               tsk.most_Resent_Campaign__c = thiscpn.Description;
            
               system.debug('++++++ the tsk.most_Resent_Campaign__c value is +++++++'+tsk.most_Resent_Campaign__c);
               
                  }            
                }       
            
              }
            
            }
         }
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger updateDescription caused an unexpected exception, contact your administrator: updateDescription: execution of BeforeUpdate caused by: System.StringException: Invalid id: sfdc salesforce sfdc : Trigger.updateDescription: line 37, column 1
HI Viewers,
i have two  fields   converteddate__C(Date) and submittedDate__c(Date/Time)  in lead object and having  formula field Duration scince converted.Here "Dutation_since_converted =  converteddate__C - Datevalue(submittedDate__c) "..  i want  calculate only weekdays. i write a formula , i am getting  duration_since_converted. But i want exclude weeends in this ?How to wrt formula for exclude weekends can any one can help me please .

Thanks!
Sreeni sree
Hi Viewers,

i want sent email when click on detail page custom button in opportunity obj. &update the fields 
1. send an email partner
2.channel manager(account owner of partner account)
3.account owner
4. fields should be updated like date= today,stage='duplcate',status= 'rejected'.


​can any one help me .
Challenge not yet complete in My Trailhead Playground 1
There was an unexpected error in your org which is preventing this assessment check from completing: System.CalloutException: IO Exception: Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://th-apex-soap-service.herokuapp.com/parks
sfdc flocks can you give me  help on below code .

Method does not exist or incorrect signature: void put(Decimal, String) from the type Map<Id,String> at line 8 column 24

trigger changeowner on Lead (before insert) {
     Map<Id,String> zipCodeUserMap = new Map<Id,String>();
     List<Zip_Code__c> zipCodes = new List<Zip_Code__c>();
     zipCodes = [Select id,ZipCode__c,Counserlor__c  from Zip_Code__c];
      
      for (Zip_Code__c zc :zipCodes){
        
        zipCodeUserMap.put(zc.ZipCode__c,zc.Counserlor__c);   
     }
       
       
       
       for(Lead l : Trigger.new) 
       {
        if(zipCodeUserMap.containsKey(l.Zip_Code__c)) 
        {
            l.Ownerid = zipCodeUserMap.get(l.Zip_Code__c);
        }
       }
}
HI Everyone,

I have a confusion about Helper and Handler classes.
Can some please explain briefly what are those?

Thanks in advance

hi viewers: i have two fields in task obj most recent campaign (lookup to campaign)  and description , i want to update the description  as mosot resend campaign (lookup to campaign ) in task.. using before trigger. i wrote some logic  updateDescription on Task (Before insert,Before Update) . i am getting fallowing error when i am create record. any one help me .


{

            set<id> setcmpnid =new set<id>();
            
            for(task tsk:trigger.new)
              {
                String wId = tsk.WhatId;
                
                if(wId!=null && !setcmpnid.contains(tsk.WhatId))
                { 
                  setcmpnid.add(tsk.WhatId);
                  system.debug('++++++ the setcmpnid  value is +++++++'+setcmpnid);
                } 
            }
            
            if(setcmpnid.size()>0) {
            
            list<campaign> tskcmpn= [Select id, Description from campaign where id in :setcmpnid ];
            
            Map<id,campaign> cmpn= new Map<id,campaign>();
               for(campaign cpn : tskcmpn)
              {
                  cmpn.put(cpn.Id,cpn); 
                   system.debug('++++++ the campaign id value is +++++++'+cmpn);
              }
            
              for (task tsk:trigger.new) {
                                
                String wId = tsk.WhatId; 
            
               if(wId!=null) { 
                  
               campaign thiscpn = cmpn.get(tsk.WhatId);  
               
               if(thiscpn != null){
               
               tsk.most_Resent_Campaign__c = thiscpn.Description;
            
               system.debug('++++++ the tsk.most_Resent_Campaign__c value is +++++++'+tsk.most_Resent_Campaign__c);
               
                  }            
                }       
            
              }
            
            }
         }
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger updateDescription caused an unexpected exception, contact your administrator: updateDescription: execution of BeforeUpdate caused by: System.StringException: Invalid id: sfdc salesforce sfdc : Trigger.updateDescription: line 37, column 1
Hi Viewers,

i want sent email when click on detail page custom button in opportunity obj. &update the fields 
1. send an email partner
2.channel manager(account owner of partner account)
3.account owner
4. fields should be updated like date= today,stage='duplcate',status= 'rejected'.


​can any one help me .
"myfirstcontapp" is a Namespace Prefix

Code for AnimalLocator Class:
public class AnimalLocator{
   public static String getAnimalNameById(Integer id){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        String strResp = '';
        system.debug('******response '+response.getStatusCode());
        system.debug('******response '+response.getBody());
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200){
            // Deserializes the JSON string into collections of primitive data types.
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            // Cast the values in the 'animals' key as a list
            Map<string,object> animals = (map<string,object>) results.get('animal');
            System.debug('Received the following animals:' + animals );
            strResp = string.valueof(animals.get('name'));
            System.debug('strResp >>>>>>' + strResp );
        }
        return strResp ;
    }
}


Code for AnimalLocatorMock Mock Class
@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}');
        response.setStatusCode(200);
        return response; 
    }
}
Code for AnimalLocatorTest​  Test Class:
@isTest
public class AnimalLocatorTest {
  @isTest public static void AnimalLocatorMock() {
       //Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
      test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
        string result = AnimalLocator.getAnimalNameById(1);
      system.debug(result);
        String expectedResult = 'chicken';
        System.assertEquals(result,expectedResult );
    }
}
Thanks
I'm stuck trying to access Einstein Platform Account. It says my email is already registered, but I have no way to get in. PEM? HELP please.
Hello,

I created an Apex class to be launched after a sandbox refresh.
I am trying to implement the test class corresponding but I got the following error :
Method does not exist or incorrect signature: Test.testSandboxPostCopyScript(SandboxPostRefresh, Id, Id, String)
Someone already had this error ? My class is set on version 38.

Here is my test class :
@isTest
private class SandboxPostRefreshTest {
	
	@isTest static void testSandboxPostRefresh() {
		Test.startTest();
		SandboxPostRefresh ClassInstance = new SandboxPostRefresh();
		System.Test.testSandboxPostCopyScript(ClassInstance, UserInfo.getOrganizationId(), UserInfo.getOrganizationId(), 'sandboxName');
		Test.stoptest();
	}	
}

And my post refresh class :
global class SandboxPostRefresh {
	global void runApexClass(SandboxContext context) {
		NexthinkProvider np = NexthinkProvider.getInstance();
		String[] opportunityRecordTypes = new String[]{'New Customer','NBS','Services','Renewal','Upsell'};
		Schema.DescribeSObjectResult oSchema = Schema.SObjectType.Opportunity;
		Map<String,Schema.RecordTypeInfo> rtMapByName = oSchema.getRecordTypeInfosByName();

		// Create accounts
		List<Map<String, Object>> accountsProperties = new List<Map<String, Object>>();
		for (Integer i = 1; i <= 13; i++) {
			String industry = Randomizer.getRandomPickListValue(Account.sObjectType, null, 'Industry', false);
			Account a = new Account();
			Randomizer.getRandomPickListValue(null, a, 'Industry', false);
		    Map<String, Object> accountProperties = new Map<String, Object>();
		    if(i == 13) {
				accountProperties.put('Name', 'Direct');
		    }
		    else {
				accountProperties.put('Name', Randomizer.getRandomCompanyName());
			}
			accountProperties.put('Industry', Randomizer.getRandomPickListValue(Account.sObjectType, null, 'Industry', false));
			if(i <= 3) {
				accountProperties.put('Type', 'Potential Customer');
			}
			else if(i > 3 && i <= 6) {
				accountProperties.put('Type', 'Customer');
			}
			else if(i > 6 && i <= 9) {
				accountProperties.put('Type', 'Potential Partner');
				accountProperties.put('Industry', 'Technology');
			}
			else if(i > 9 && i <= 13) {
				accountProperties.put('Type', 'Partner');
				accountProperties.put('Industry', 'Technology');
			}
			accountProperties.put('CurrencyIsoCode', Randomizer.getRandomCurrency());
			accountProperties.put('Country__c', Randomizer.getRandomCountry());
			accountsProperties.add(accountProperties);
		}
		List<Account> accounts = np.createAccounts(accountsProperties);

		List<Account> partners = new List<Account>();
		for(Account a : accounts) {
			if(a.Type == 'Potential Partner' || a.Type == 'Partner') {
				partners.add(a);
			}
		}

		
		List<Map<String, Object>> contactsProperties = new List<Map<String, Object>>();
		List<Map<String, Object>> opportunitesProperties = new List<Map<String, Object>>();
		for(Account a : accounts) {
			// Create contacts
			Map<String, Object> contactProperties = new Map<String, Object>();
			contactProperties.put('FirstName', Randomizer.getRandomFirstname());
			contactProperties.put('LastName', Randomizer.getRandomLastname());
			contactProperties.put('Phone', Randomizer.getRandomPhoneNumber());
			contactProperties.put('AccountId', a.Id);
			String firstname = (String) contactProperties.get('FirstName');
			String lastname = (String) contactProperties.get('LastName');
			contactProperties.put('Email', firstname.toLowerCase() + '.' + lastname.toLowerCase() + '@' + a.Name.toLowerCase() + '.com');
			contactProperties.put('Country__c', a.Country__c);
			contactProperties.put('LeadSource', Randomizer.getRandomPickListValue(Contact.sObjectType, null, 'LeadSource', false));
			contactsProperties.add(contactProperties);
			if(a.Name != 'Direct' && a.Type != 'Partner' && a.Type != 'Potential Partner') {
				for (Integer i = 1; i <= 3; i++) {
					// Create opportunities
					Map<String, Object> opportunityProperties = new Map<String, Object>();
					
					String partnerName;
					if(Randomizer.getRandomBoolean()) {
						Account partner = partners.get(Randomizer.getRandomNumber(6));
						partnerName = partner.Name;
						opportunityProperties.put('Partner_Lookup__c', partner.Id);
					}
					else {
						partnerName = 'Direct';
					}

					Schema.RecordTypeInfo rt = rtMapByName.get(Randomizer.getRandomString(opportunityRecordTypes));
					opportunityProperties.put('RecordTypeId', rt.getRecordTypeId());
					opportunityProperties.put('Name', a.Name + '_' + partnerName + '_' + rt.getName());
					opportunityProperties.put('AccountId', a.Id);
					opportunityProperties.put('CurrencyIsoCode', a.CurrencyIsoCode);
					opportunityProperties.put('CloseDate', Date.today().addDays(Randomizer.getRandomNumber(90)));
					opportunityProperties.put('StageName', 'Unqualified');
					opportunityProperties.put('Probability', 11);
					opportunityProperties.put('LeadSource', Randomizer.getRandomPickListValue(Opportunity.sObjectType, null, 'LeadSource', false));
					opportunityProperties.put('Contract_Start_Date__c', ((Date) opportunityProperties.get('CloseDate')).addDays(1));
					String contractCommitment = Randomizer.getRandomPickListValue(Opportunity.sObjectType, null, 'Contract_Commitment__c', false);
					opportunityProperties.put('Contract_Commitment__c', contractCommitment);
					if(contractCommitment == '<1 Year') {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(90));
					}
					else if(contractCommitment == '1 Year') {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(Randomizer.getRandomNumber(365)));
					}
					else if(contractCommitment == '2 Years') {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(365*2));
					}
					else if(contractCommitment == '3 Years') {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(365*3));
					}
					else if(contractCommitment == '4 Years') {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(365*4));
					}
					else if(contractCommitment == '5 Years') {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(365*5));
					}
					else {
						opportunityProperties.put('Contract_End_Date__c', ((Date) opportunityProperties.get('Contract_Start_Date__c')).addDays(500));
					}
					opportunitesProperties.add(opportunityProperties);
				}
			}
		}
		List<Contact> contacts = np.createContacts(contactsProperties);
		List<Opportunity> opportunities = np.createOpportunities(opportunitesProperties);

		// Get all products
		Map<String, Product2> productsMap = new Map<String, Product2>(); 
		for(Product2 product : [SELECT Id, Name FROM Product2]) {
			productsMap.put(product.Name, product);
		}
        
        // Create OpportunityLineItem
		Map<Opportunity,List<Object>> olisMap = new Map<Opportunity,List<Object>>();
		for(Opportunity o : opportunities) {
			List<Object> tempList = new List<Object>();
			List<Product2> opportunityProductList = new List<Product2>();
			Map<String, Object> oliProperties = new Map<String, Object>();
			oliProperties.put('Description', 'SKU');
			
			if(o.RecordTypeId == rtMapByName.get('New Customer').getRecordTypeId() || o.RecordTypeId == rtMapByName.get('Upsell').getRecordTypeId()) {
				oliProperties.put('Quantity', 100);
				opportunityProductList.add(productsMap.get('Endpoint Collector - License'));
				if(Randomizer.getRandomBoolean()) {
					opportunityProductList.add(productsMap.get('Endpoint Collector - Maintenance 1yr'));
				}
				else {
					opportunityProductList.add(productsMap.get('Endpoint Collector - Subscription 1yr'));
				}
				if(Randomizer.getRandomBoolean()) {
					opportunityProductList.add(productsMap.get('Time & Material billed upon completion - per day'));
				}
			}
			if(o.RecordTypeId == rtMapByName.get('NBS').getRecordTypeId()) {
				oliProperties.put('Quantity', 5);
				opportunityProductList.add(productsMap.get('Baseline Service 1-Engine'));
			}
			if(o.RecordTypeId == rtMapByName.get('Renewal').getRecordTypeId()) {
				oliProperties.put('Quantity', 1000);
				if(Randomizer.getRandomBoolean()) {
					opportunityProductList.add(productsMap.get('Renewal Endpoint Collector - Subscription 1yr'));
				}
				else {
					opportunityProductList.add(productsMap.get('Renewal Endpoint Collector - Maintenance 1yr'));
				}
			}
			if(o.RecordTypeId == rtMapByName.get('Services').getRecordTypeId()) {
				oliProperties.put('Quantity', 10);
				Integer random = Randomizer.getRandomNumber(3);
				if(random == 1) {
					opportunityProductList.add(productsMap.get('Time & Material billed upon completion - per day'));
				}
				else if(random == 2) {
					opportunityProductList.add(productsMap.get('Service Fee Billed in Advance'));
				}
				else if(random == 3) {
					opportunityProductList.add(productsMap.get('Fixed fee billed upon milestone completion'));
				}
			}
			tempList.add(opportunityProductList);
			tempList.add(oliProperties);
			olisMap.put(o, tempList);
		}
		np.addProducts(olisMap);
	}
}

 
Batch class as exposed as interface implement by developer.it is helpful for handle large number of records.Please explain real time exmple why we need to use Batch class  in real time?
public class VerifyDate {
//method to handle potential checks against two dates
public static Date CheckDates(Date date1, Date date2) {
//if date2 is within the next 30 days of date1, use date2. Otherwise use the end of the month
if(DateWithin30Days(date1,date2)) {
return date2;
} else {
return SetEndOfMonthDate(date1);
}
}
//method to check if date2 is within the next 30 days of date1
private static Boolean DateWithin30Days(Date date1, Date date2) {
//check for date2 being in the past
if( date2 < date1) { return false; }
//check that date2 is within (>=) 30 days of date1
Date date30Days = date1.addDays(30); //create a date 30 days away from date1
if( date2 >= date30Days ) { return false; }
else { return true; }
}
//method to return the end of the month of a given date
private static Date SetEndOfMonthDate(Date date1) {
Integer totalDays = Date.daysInMonth(date1.year(), date1.month());
Date lastDay = Date.newInstance(date1.year(), date1.month(), totalDays);
return lastDay;
}
}

I need test class for this class.Please provide me
Hello developer heroes!

I'm working through the Apex modules on Trailhead and can't seem to get past this one: https://developer.salesforce.com/en/trailhead/force_com_programmatic_beginner/apex_triggers/apex_triggers_bulk.

Hopefully this doesn't read like a 'please complete the course for me' kinda post, but I have written a trigger that I believe meets the criteria but it isn't passing the check, so I wanted to seek the guidance of the experts.

The challenge is to do this:

Create an Apex trigger for Opportunity that adds a task to any opportunity set to 'Closed Won'.

To complete this challenge, you need to add a trigger for Opportunity. The trigger will add a task to any opportunity inserted or updated with the stage of 'Closed Won'. The task's subject must be 'Follow Up Test Task'.The Apex trigger must be called 'ClosedOpportunityTrigger'

- With 'ClosedOpportunityTrigger' active, if an opportunity is inserted or updated with a stage of 'Closed Won', it will have a task created with the subject 'Follow Up Test Task'.
- To associate the task with the opportunity, fill the 'WhatId' field with the opportunity ID.
- This challenge specifically tests 200 records in one operation.


And here is the trigger I have come up with, which compiles OK and stands up to a manual (though admittedly unbulkified) test:
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {

    List<Task> taskList = new List<Task>();
    
    for (Opportunity opp : [SELECT Id, StageName FROM Opportunity WHERE StageName = 'Closed Won' AND Id IN :Trigger.new]){
                    
            taskList.add(new Task(Subject = 'Follow Up Test Task',
                                  WhatId = opp.Id));
       
    }

    if(taskList.size()>0){
        
        insert taskList;
        
    }
    
}
I have tried replacing the SOQL with a straightforward 'for (Opportunity opp : Trigger.new)' and having the taskList.add inside an IF that checks for Closed Won - no luck. I also thought about checking to see if the stage was being changed to Closed Won, rather than the trigger firing on every edit, but I don't think this is what the module is asking for.

Where do you think I'm going wrong?

Huge thanks in advance!