• MedhanieHabte
  • NEWBIE
  • 150 Points
  • Member since 2015
  • Developer Account


  • Chatter
    Feed
  • 1
    Best Answers
  • 6
    Likes Received
  • 0
    Likes Given
  • 19
    Questions
  • 34
    Replies
I've been working on this trail for a bit - and while I undertsand the concepts, I'm stumped on why I'm getting this error: 
 
Challenge Not yet complete... here's what's wrong: 
A Create a Record action for the Closed Won criteria node isn't properly configured. Make sure that it creates a draft contract according to the instructions in the ‘Create contract for closed opportunity’ task action. Make sure that Start Date is set by using a formula.

I've gone over all of the workflow tasks information to recreate the contact. If I activate the process and close an opportunity, it creates a contract with the expected information and the date is 1mo away with 12mo term. The workflow's task (which is the template for the actual contract) specifies the following: 
 
Use the closed opportunity to create a contract for the associated account. 

Account: The account associated with this opportunity
Status: Draft
Contract Start Date: 1 month from today
Contract Term: 12
Here are my actions: 
User-added image

The Contract Start Date is set to the following formula:
DATE(
    YEAR(Today()) +
    FLOOR((1 + MONTH(Today())) / 12) -
    IF (MOD(MONTH(Today()) + 1, 12) = 0,
        1,
        0),

    MOD((1 + MONTH(Today()) - 1), 12) + 1,

    DAY(Today())
)

Again, for all practical purposes I'm passing this, as it functions and the contract is created. But I must be missing some small detail, named field, something that's tripping up the validation settings. Any help is appreciated!

 
Greetings all, I seem to be stuck on the Use the Salesforce Lightning Design System to Style Visualforce Pages module, I modeled my contact page but can't seem to get the contact's to display, any steps others have taken?
Greetings all, I've created this apex trigger to create a child case record when a few words are found in the description of a parent case record such as social security, credit cards, etc. What I am trying to do, however, is have the child case record create with a description that only contains the words found in the parent case description. These words are captured in the secretKeyword set.

I tried using the .split method in my string, but get this error that such methods don't exist, any steps I should take.

triggers/CheckSecretInformation.trigger: Method does not exist or incorrect signature: void split(String) from the type Set<String> 

 
trigger CheckSecretInformation on case (after insert, before update) {
	
	String childCaseSubject = 'Waring: Parent case may contain secret info';

	// Step 1: Create a collection containing each of our secret keywords
	Set<String> secretKeywords = new Set<String>();
	secretKeywords.add('Credit Cards');
	secretKeywords.add('Social Security');
	secretKeywords.add('SSN');
	secretKeywords.add('Passport');
	secretKeywords.add('Bodyweight');

// Step 2: Check to see if our case contains any of the secret words
	List<Case> casesWithSecretInfo = new List<Case>();
	for(Case myCase : Trigger.new){		
		if (myCase.Subject != childCaseSubject) {
		for (String Keyword : secretKeywords) {
			if(myCase.Description != null && myCase.Description.containsIgnoreCase(Keyword)) {
				casesWithSecretInfo.add(myCase);
				System.debug('Case ' + myCase.Id + ' include secret keywords' + keyword);
				break;
				}
			}
		}
	}
	// Step 3: If our case contains a secret keyword, create a child case
	List<Case> casesToCreate = new List<Case>();
	  System.debug('Size of offending cases: ' + casesWithSecretInfo.size());


	for (Case casesWithSecretInfo : casesWithSecretInfo) {
		Case childCase        = new Case();
		childCase.Subject     = childCaseSubject;
		childCase.ParentId    = casesWithSecretInfo.Id;
		childCase.IsEscalated = true;
		childCase.Priority    = 'High';
		childCase.Description = 'At least one of the following keywords were found:' + secretKeywords.split(;);
		casesToCreate.add(childCase);
	}
	insert casesToCreate;
}



 

Hi all, I am so close to finishing this process automation badge but am stuck in one area in Step 7.

I've built out my process builder as follows

User-added image
User-added image
User-added image

And my date formula as follows
 

Case(MOD(Date__c-DATE(1900,1,7),7),0,"Sunday",1,"Monday",2,"Tuesday",3,"Wednesday",4,"Thursday",5, "Friday",6,"Saturday", "")
 



Challenge Not yet complete... here's what's wrong:  The Robot Setup Day of the Week formula does not seem to be working properly. The Day of the Week should not fall on Saturday or Sunday. 

It works nicely but doesn't seem to pass, what could be up.
 

Hi all,

I am working on a 3D Virtual Reality app Trailhead and seem to be stuck with building out the app. I encounter this error.

"Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.  See the Console for details."
 
Error:Invalid command android

UnityEditor.PostprocessBuildPlayer:PrepareForBuild(BuildOptions, BuildTargetGroup, BuildTarget)
 
CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details. 
/Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home/bin/java -Xmx2048M -Dcom.android.sdkmanager.toolsdir="/Users/medhaniehabte/Library/Android/sdk/tools" -Dfile.encoding=UTF8 -jar "/Applications/Unity/PlaybackEngines/AndroidPlayer/Tools/sdktools.jar" -

stderr[
Error:

I have correctly set up android studio and SDK and assigned the right directory, but when I get to building, I am stuck, any steps I should take.
Greetings, I am working on the Salesforce Build a 3D Virtual Reality App project in trailhead and have downloaded Unity and Google's VR tools, but when I attempt to install the VR toolkit, I encounter this error?

Assets/Salesforce/Components/Scripts/Trigger.cs(24,51): error CS0246: The type or namespace name `GazeInputModule' could not be found. Are you missing an assembly reference?

Anything that I am missing.
Greetings, 

Our organization is using a Shiny R map to display data from various locations across the region. We chose the Shiny R map as it enables us to display more records than our salesforce org could handle. In essence, a customer can click a location which determines if a location exists, if so, the customer can then view data on the record. If not, a customer can create a record with the data fields prefilled to create the record. Has anyone experimented with this process, are there any suggestions, that might make sense.
 
Greetings, I've created my external object for the Data Integration Specalist Superbadge and have configured my external ID as seen below, however, the challenge seems to not pass, indicating that the indirect lookup was not properly created. Here's how I set up the projectRef__c field, which was what I used to push data from the external object into the project object in Salesforce. Are there any steps, I need to take. Hope it helps.
User-added image


User-added image
 
Hi all, I seem to be stuck on authoring the class and test classes on the Superbadge Data Integration Specialist. I have authored the ProjectCalloutService plus the test class and HTTPCallouts, but encounter a Null pointer exception error at line 35:1

Anything I should add to the code. I have built the process builder as needed.

Project Callout Service
public class ProjectCalloutService {
    public static Id opportunityId;
    
    @InvocableMethod
    public static void postOpportunityToPMS(List<Id> opportunityIds){
        opportunityId=opportunityIds.get(0);
        Opportunity opp=[Select Id,Name, closeDate,amount,Account.Name FROM Opportunity Where Id =: opportunityId];
        ID jobID = System.enqueueJob(new QueueablePMSCall(opp));
    }    
    
    public class QueueablePMSCall implements system.Queueable,Database.AllowsCallouts
    {
        private String jsonOpp;
        private Opportunity opportunityObject;
        public QueueablePMSCall(Opportunity opp)
        {
            opportunityObject=opp;
            JSONGenerator gen = JSON.createGenerator(true);
            gen.writeStartObject();
            gen.writeStringField('opportunityId', opp.Id);
            gen.writeStringField('opportunityName', opp.Name);
            gen.writeStringField('accountName', opp.account.Name);
            gen.writeDateField('closeDate', opp.closeDate);
            gen.writeNumberField('amount', opp.amount);
            
            gen.writeEndObject();            
            
            jsonOpp= gen.getAsString();
            System.debug('jsonOpp: ' + jsonOpp);
            
        }
        public void execute(QueueableContext context) {
            
            ServiceTokens__c token= ServiceTokens__c.getValues('ProjectServiceToken');
            System.debug(token.Token__c);
            
            // create an HTTPrequest object    
            HttpRequest req = new HttpRequest();
            req.setMethod('POST');
            req.setEndpoint('callout:ProjectService/'+ token.Token__c);
            req.setHeader('Content-Type', 'application/json');
            req.setBody(jsonOpp);    
            
            // create a new HTTP object
            Http http = new Http();
            HTTPResponse res = http.send(req);
            if (res.getStatusCode() != 201) {
                System.debug('Error from ' + req.getEndpoint() + ' : ' +
                             res.getStatusCode() + ' ' + res.getStatus());
                
                Opportunity opportunity1=[Select Id, StageName FROM Opportunity Where Id =: opportunityObject.Id];
                opportunity1.StageName='Resubmit Project';
                update opportunity1;
                
            }
            else {
                Opportunity opportunity2=[Select Id, StageName FROM Opportunity Where Id =: opportunityObject.Id];
                opportunity2.StageName='Submitted Project';
                update opportunity2;
            }      
        }
        
    } 
}
Test Class
@isTest
private class ProjectCalloutServiceTest {
  //Implement mock callout tests here
  public static testMethod void testSuccess(){
      Account acc = new Account(Name='Test Account');
      insert acc;
      Opportunity opp = new Opportunity(Name='Test Opportunity',
                        AccountId=acc.id, CloseDate=System.Today(),
                        Amount=12480.00,
                        Type='New Project',
                        StageName='Qualification');
      insert opp;
      Test.startTest();
      Test.setMock(HttpCalloutMock.class, new ProjectCalloutServiceMock());
      Test.stopTest();
      opp.StageName='Closed Won';
      update opp;
      
  }
  public static testMethod void testFailure(){
      Account acc = new Account(Name='Test Account');
      insert acc;
      Opportunity opp = new Opportunity(Name='Test Opportunity',
                        AccountId=acc.id, CloseDate=System.Today(),
                        Amount=12480.00,
                        Type='New Project',
                        StageNAme='Qualification');
      insert opp;
      Test.startTest();
      Test.setMock(HttpCalloutMock.class, new ProjectCalloutServiceMockFailure());
      Test.stopTest();
      opp.StageName='Closed Won';
      update opp;
  }
}

HTTP Callout Success
global class ProjectCalloutServiceMock implements HttpcalloutMock{
   //Implement http mock callout here
   global HttpResponse respond(Httprequest request){
       HttpResponse response = new Httpresponse();
       String resBody = '[Status=Created, StatusCode=201]';
       response.setHeader('Content-Type','application/json');
       response.setBody(resBody);
       response.setStatusCode(201);
       return response;
   }
}
HTTP Callout Fail
 
//ProjectCalloutServiceMockFailure
global class ProjectCalloutServiceMockFailure implements HttpcalloutMock{
   //Implement http mock callout failure here 
   //Implement http mock callout here
   global HttpResponse respond(Httprequest request){
       HttpResponse response = new Httpresponse();
       String resBody = '[Status=Created, StatusCode=501]';
       response.setBody(resBody);
       response.setStatusCode(501);
       return response;
   }
}


 
Hi All, I am working on the Unit of Work Principles trailhead and seem to be stuck, I cannot get it to pass even though the test passes. I surmise it may be because it is testing other tests and looking for 100% code coverage across the board. Are there any steps I should take. Here is my code below. Hope it helps.
 
@isTest
public class UnitOfWorkTest {
    @isTest static void challengeComplete(){
        fflib_SObjectUnitOfWork uow = new fflib_SObjectUnitOfWork(
            new Schema.SObjectType[]{
                Account.SObjectType,
                Contact.SObjectType,
                Note.SObjectType
            }
        );
        
        for (Integer i=0 ; i<100 ; i++) {
            Account a = new Account(Name= 'Test' + i);
            uow.registerNew(a);
            
            for (Integer j=0 ; j<5 ; j++) {
                Contact c = new Contact(LastName = 'Test'+i + ' ' +j);
                uow.registerNew(c, Contact.AccountId, a);
                
                Note n = new Note(Body='Test '+i + '' + j, Title='Test'+i+j);
                //uow.registerRelationship(n, Note.ParentId, a);
                //uow.registerNew(n, Note.ParentId, a);
                uow.registerNew(n, Note.ParentId, c);
            }
        }

        uow.commitWork();
 
        fflib_SObjectUnitOfWork uow2 = new fflib_SObjectUnitOfWork(
            new Schema.SObjectType[]{
                Account.SObjectType,
                Contact.SObjectType,
                Note.SObjectType
            }
        );        
        
        Id oldAccountId;
        Account a2;
        for (Contact c : [SELECT Id, LastName, AccountId, Account.Name, (SELECT Id, ParentId, Title, Body FROM Notes) FROM Contact Order By AccountId, Id]) {
            
            if (oldAccountId != c.AccountId) {
                oldAccountId = c.AccountId;
                a2 = new Account(Id=c.AccountId, Name='Test');
                uow2.registerDirty(a2);
            }
            
                c.LastName = 'Test';
                uow2.registerDirty(c);
                

                c.Notes[0].Body = 'Test';

                uow2.registerDirty(c.Notes[0]);

        }        
        
        test.startTest();
        uow2.commitWork();
        //uow.commitWork();
        test.stopTest();
        
        System.assertEquals(100, [Select Id from Account].size());
        System.assertEquals(500, [Select Id from Contact].size());
        System.assertEquals(500, [Select Id from Note].size());
    }
}

 
Hi all, I am working on the Insecure Remote Site Trailhead and can't seem to get the image to display from a static resource zip file.

I am using this as my code
 
<apex:image url="{!URLFOR($Resource.Challenge_Resources,'Challenge_resources/Castle.png')}" />

Are there any steps I should take, hope it helps.
Greetings, I am writing a test class for a trigger that creates Opportunity Contact Roles based on the primary record. I currently have 60% code coverage and am stuck determining what steps I would need to add to achieve 75% or greater code coverage. 

Here is my trigger
trigger CreateContactRole on Opportunity (after insert, after update) {

    //get the id of all involved accounts
    Set<ID> accountIds = new Set<ID>();
    for(Opportunity opt:Trigger.New){
        accountIds.add(opt.AccountId);
    }
    
    //get all contacts for those accounts
    list<Contact> contacts = new list<Contact>();
    contacts = [select id, AccountId from Contact where AccountId in: accountIds order by createddate Limit 5000];
    
    //organize these contacts by account
    Map<Id,List<Contact>> contactsByAccount = new Map<ID,List<Contact>>();
    for(Contact c:contacts){
        if(contactsByAccount.get(c.AccountId) == null){
            contactsByAccount.put(c.AccountId,new List<Contact>());
        }
        contactsByAccount.get(c.AccountId).add(c);
    }
    
    // check to see if the Opportunity already has a contact role.  If it does, add to a set of Ids to exclude
    List<OpportunityContactRole> existingOCR = new List<OpportunityContactRole>();
    Set<Id> existingOCRIds = new Set<Id>();
    existingOCR = [select OpportunityId from OpportunityContactRole where OpportunityId in:Trigger.newMap.keySet() limit 5000];
    for(OpportunityContactRole ocr:existingOCR) if(!existingOCRIds.contains(ocr.OpportunityId)) existingOCRIds.add(ocr.OpportunityId);
    
    //create the OpportunityContactRole objects
    list<OpportunityContactRole> lstOCR = new list<OpportunityContactRole>();
    for(Opportunity opt:Trigger.New){
        if(!existingOCRIds.contains(opt.Id) && contactsByAccount.get(opt.AccountId) != null){
            Boolean firstContact = true;
            for(Contact c: contactsByAccount.get(opt.AccountId)){
                OpportunityContactRole ocr = new OpportunityContactRole(OpportunityId=opt.id, ContactId=c.id);
                if(firstContact) {
                    ocr.IsPrimary = TRUE;
                    firstContact = FALSE;
                }
                lstOCR.add(ocr);
            }
        }
    }
    insert lstOCR;
}

Here are the areas that don't appear to be covered, particularly the null pointer exception.
if(contactsByAccount.get(c.AccountId) == null){
            contactsByAccount.put(c.AccountId,new List<Contact>());
        }
        contactsByAccount.get(c.AccountId).add(c);


 
Boolean firstContact = true;
            for(Contact c: contactsByAccount.get(opt.AccountId)){
                OpportunityContactRole ocr = new OpportunityContactRole(OpportunityId=opt.id, ContactId=c.id);
                if(firstContact) {
                    ocr.IsPrimary = TRUE;
                    firstContact = FALSE;
                }
                lstOCR.add(ocr);

And here is my test class
@isTest
public class TestCreateContactRole {
    static testMethod void createAccount(){

    Account a = new Account();
    
    //First create the Account
    a.Name = 'Test Co.';
    a.BillingStreet = '298 S. Ringo Street';
    a.BillingCity = 'Little Rock';
    a.BillingState = 'AR';
    a.BillingPostalCode = '72201';
    a.BillingCountry = 'USA';
    a.Phone = '501-555-5555';
    a.Website = 'www.testco.com';
    a.Mission_Statement__c = 'We do lots of things';
    a.Facebook_URL__c = 'www.facebooktest.com';
    insert a;
    System.debug('created account');
        
    //Then create a primary contact
    Contact c = new Contact();
    c.FirstName = 'Paul';
    c.LastName  = 'Test';
    c.AccountId = a.id;
    c.MailingStreet = '298 S. Ringo Street';
    c.MailingCity = 'Little Rock';
    c.MailingState = 'AR';
    c.MailingPostalCode = '72201'; 
    c.Primary_Membership_Contact__c = TRUE;
    insert c;
    System.debug('created primary contact');
        
    //Then create another non-primary contact
    Contact ci = new Contact();
    ci.FirstName = 'Bob';
    ci.LastName  = 'Test';
    ci.AccountId = a.id;
    ci.MailingStreet = '298 S. Ringo Street';
    ci.MailingCity = 'Little Rock';
    ci.MailingState = 'AR';
    ci.MailingPostalCode = '72201'; 
    ci.Primary_Membership_Contact__c = FALSE;
    insert ci;
    System.debug('created primary contact');
        
    //Now create an opportunity
    Opportunity o = new Opportunity();
    o.RecordType = [SELECT Id, Name, DeveloperName FROM RecordType WHERE Name = 'Membership' LIMIT 1];
    o.Name = 'New Record';
    o.StageName = 'Posted';
    o.Special_Case_for_Amount_Due__c = 'No';
    o.Special_Case_for_Membership_End_Date__c = 'No';
    o.CloseDate = Date.today();
    o.npe01__Membership_Start_Date__c = Date.today();
    o.npe01__Member_Level__c = 'Nonprofit 1';
    o.Description = 'Test Record';
    insert o;
    System.debug('created opportunity');
        
    //Now update the OCR for the primary contact
    OpportunityContactRole ocr = new OpportunityContactRole();
    ocr.ContactId = c.Id;
    ocr.OpportunityId = o.Id;
    ocr.IsPrimary = TRUE;
    ocr.Role = 'Decision Maker';
    insert ocr;
    System.debug('created opportunity contact role for primary');
        
    //Now update the OCR for the non-primary contact
    OpportunityContactRole ocr1 = new OpportunityContactRole();
   	    
    ocr1.ContactId = ci.Id;
    ocr1.OpportunityId = o.Id;
    ocr1.IsPrimary = FALSE;
    ocr1.Role = 'Decision Maker';
    insert ocr1;
    System.debug('created opportunity contact role for non-primary contact');
                
}
}

I'm fairly new to Apex, but would love to learn more. Hope it helps.
Hi all, I am stuck on the prevent SOQL injection trailhead, where I am looking to determine which portions of the code I would need to invoke escapeSingleQuotes or whitelist to enable. I've made several attempts at investigation to little avail. I have appended my code are there any steps I would need to take. My goal is to assess the code to see how it works and what I would need to do.

Hope it helps.
 
public class Prevent_SOQL_Injection_Challenge {

    public string textOne {get; set;}
    public string textTwo {get; set;}
    public string comparator {get; set;}
    public string numberOne {get; set;}

    public List<Supply__c> whereclause_records {get; set;}


    public PageReference stringSearchOne(){
        string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';
        string whereClause = '';

        if(textOne != null && textOne!=''){
                whereClause += 'name like  \'%'+textOne+'%\' ';
        }

        if(whereClause != ''){
            whereclause_records = database.query(query+' where '+whereClause+' Limit 10');
        }

        return null;
    }


    public PageReference stringSearchTwo(){
        string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';
        string whereClause = '';

        if(textTwo != null && textTwo!=''){
                whereClause += 'Storage_Location__r.name like  \'%'+textTwo+'%\' ';
        }

        if(whereClause != ''){
            whereclause_records = database.query(query+' where '+whereClause+' Limit 10');
        }

        return null;
    }


    public PageReference numberSearchOne(){
        string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';
        string whereClause = '';

        if(numberOne != null && comparator != null){
            whereClause += 'Quantity__c '+comparator+' '+numberOne+' ';
        }

        if(whereClause != ''){
            whereclause_records = database.query(query+' where '+whereClause+' Limit 10');
        }

        return null;
    }

}

 
Greetings, I am working on the Prevent XSS in Force.Com Applications Trailhead, so far I've gotten most of the sections cleared. However, I seem to be stuck with this one. I've attempted many ways to assign JSENCODE, HTMLENCODE and JSINHTMLENCODE where needed but seem to stuck, are there any steps I should take here. My code's below. Hope it helps!
 
<apex:page controller="XSS_Mitigations_Challenge" sidebar="false" tabStyle="XSS_Mitigations_Challenge__tab">
<apex:sectionHeader title="XSS Mitigations Challenge" />
<apex:form >
    <apex:pageBlock >
        <apex:pageMessages />      
        <apex:pageBlockSection title="Demo" columns="1" id="tableBlock">
            <c:codeLink type="Visualforce" namespace="" edit="true" name="XSS_Mitigations_Challenge" description="Edit this Visualforce page to perform the challenge."/>
            
            
            <apex:outputText value="{!JSENCODE(sampleMergeField1)}"/>


            <apex:outputText value="{!HTMLENCODE(sampleMergeField2)}" escape="false"/>


            <apex:outputText >
                {!sampleMergeField3}
            </apex:outputText>
       
       
            <script>
                document.write('{!JSENCODE(sampleMergeField4)}');
            </script>
             
            
            {!sampleMergeField5}
            
            
            <script>
                var x = '{!JSENCODE(sampleMergeField6)}';
            </script>
            
            
            <apex:outputLabel value="{!sampleMergeField7}" escape="false"/>
                     

        </apex:pageBlockSection>
        <apex:pageBlockSection title="Code links" columns="1">
            <apex:outputPanel >
                <ul>
                    <li><c:codeLink type="Visualforce" namespace="" name="XSS_Mitigations_Challenge" description="Visualforce Page"/></li>            
                    <li><c:codeLink type="Apex" namespace="" name="XSS_Mitigations_Challenge" description="Apex Controller"/></li>
                </ul>
            </apex:outputPanel>        
        </apex:pageBlockSection>        
    </apex:pageBlock>          
</apex:form>              
</apex:page>

 
Greetings, I have developed some code for Step 5 in the Superbadge, but appear to stuck as I run the test. I am encountering an error and attempting to determine how to configure my code to pass the test. Are there any steps I am missing? I've covered much of the superbadge, but remain stuck here. 

User-added image

WarehouseCalloutServiceTest
@isTest
public class WarehouseCalloutServiceTest {
  // implement your mock callout test here
    testMethod Static void test(){
        List<EquipmentWrapperFromJSON> ListEWFS = new List<EquipmentWrapperFromJSON>();
        List<Product2> listProduct = new List<Product2>();
        Product2 p = new Product2();
        p.Replacement_Part__c = true;
        p.Name = 'testing';
        p.Cost__c = 10;
        p.Current_Inventory__c = 5;
        p.Lifespan_Months__c = 2;
        p.Maintenance_Cycle__c = 60;
        p.Warehouse_SKU__c = '10001';
        listProduct.add(p);

        insert listProduct;

        test.startTest();
            //ListEWFS = WarehouseCalloutService.wrapWquipment();
            Test.setMock(WebServiceMock.class, new WarehouseCalloutService());
            WarehouseCalloutService.runWarehouseEquipmentSync();
        test.stopTest();
        Upsert listProduct;
    }
}

MockHttpResponseGenerator
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('http:///th-superbadge-apex.herokuapp.com', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"equipment":[{"id":"55d66226726b611100aaf741","replacement":false,"quantity":5,"name":"Generator 1000 kW","maintenanceperiod":365,"lifespan":120,"cost":5000,"sku":"100003"}, {"id":"55d66226726b611100aaf742","replacement":true,"quantity":183,"name":"Cooling Fan","maintenanceperiod":0,"lifespan":0,"cost":300,"sku":"100004"}]}');
        res.setStatusCode(200);
        return res;
    }
}

WarehouseCalloutService
public with sharing class WarehouseCalloutService {
    
    private static final String WAREHOUSE_URL = 'https://th-superbadge-apex.herokuapp.com/equipment';
    @future(callout=true)
    // complete this method to make the callout (using @future) to the
    // REST endpoint and update equipment on hand.
    public static void runWarehouseEquipmentSync(){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(WAREHOUSE_URL);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        // If the request is successful, parse the JSON response.
        String ret = '';
        if (response.getStatusCode() == 200) {
            // Deserialize the JSON string into collections of primitive data types.
            List<Object> results = (List<Object>) JSON.deserializeUntyped(response.getBody());
            
            List<Product2> LstProduct = new List<Product2>();
            for(Object obj : results)
            { 
                Map<String, Object> mapobj = (Map<String, Object>)obj;
                Product2 product = new Product2();
                           
                Integer maintenanceperiod = (Integer)mapobj.get('maintenanceperiod');               
                Integer Lifespan = (Integer)mapobj.get('lifespan');
                Integer Cost = (Integer)mapobj.get('cost');
                Boolean replacement = (Boolean)mapobj.get('replacement');
                Integer quantity = ((Integer)mapobj.get('qIntegerntity'));
                product.Name  = (String)mapobj.get('name'); 
                product.Maintenance_Cycle__c = Integer.valueof(maintenanceperiod);
                product.Cost__c = Cost;
                product.Current_Inventory__c = quantity;
                product.Lifespan_Months__c = Lifespan; 
                product.Replacement_Part__c = replacement;
                product.Warehouse_SKU__c = (String) mapobj.get('sku');
                product.ProductCode = (String)mapobj.get('_id');       
                LstProduct.add(product);
            }
            System.debug(LstProduct);
            upsert LstProduct Warehouse_SKU__c;
        }
        
    }
}

 
Greetings I am running into the error, when attempting to verify step 3 in the superbadge challenge. I have created everything I needed but still seem to be stuck. Any steps I need to take, hope it helps.

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error while verifying this challenge. Usually this is due to some pre-existing configuration or code in the challenge Org. We recommend using a new Developer Edition (DE) to check this challenge. If you're using a new DE and seeing this error, please post to the developer forums and reference error id: LELXAKDE

User-added image
Greetings,

I am wondering if there is a way to create an Apex Trigger to notify a contact owner, when an opportunity is created with a primary contact populated in the contact role. We have a template available too, but worst case scenario, I can incorporate the message in Salesforce. 

Hope it helps.
Greetings, I've been working with Jeff Douglas' Roll Your Salesforce Lookup (http://blog.jeffdouglas.com/2011/08/12/roll-your-own-salesforce-lookup-popup-window/) as part of an app I've been building in our org. This app serves to replace the dreaded quickcreate system and allows for the inline creation of contact records, should they not be available.

One of the initial issue we have encountered is the inability to look up or add contact records with quotes (') in their first or last name as part of the query. This returns an exception error. A step I took to address was to escapesinglequote, which allows for looking up contacts with ('). Now with Single Quote escaped, I am unable to close the popup when I create new records or select a record with a (') in the result. I'm certain this may have to do with the code in the VF page. I am wondering what steps I need to take.

Are there any steps, I can take to address. Class and Page attached below.

Class
public class ContactLookupControl {

  public Contact contact {get;set;} // new contact to create
  public List<Contact> results{get;set;} // search results
  public string searchString{get;set;} // search keyword

  public ContactLookupControl() {
    contact = new Contact();
    // get the current search string
    searchString = System.currentPageReference().getParameters().get('lksrch');
    runSearch();  
  }

  // performs the keyword search
  public PageReference search() {
    runSearch();
    return null;
  }

  // prepare the query and issue the search command
  private void runSearch() {
    // TODO prepare query string for complex serarches & prevent injections
    results = performSearch(searchString);               
  } 

  // run the search and return the records found. 
  private List<Contact> performSearch(string searchString) {

    String soql = 'select id, name,account.Name,MailingStreet,MailingCity,MailingState,MailingPostalCode,MailingCountry,Phone,Email from contact';
    if(searchString != '' && searchString != null)
      soql = soql +  ' where name LIKE \'%' + searchString +'%\'';
    soql = soql + ' limit 25';
    System.debug(soql);
    return database.query(soql); 

  }

  // save the new contact record
  public PageReference saveContact() {
    insert contact;
    contact=[select id,name,FirstName,LastName,AccountId,MailingStreet,MailingCity,MailingState,MailingPostalCode,MailingCountry,Phone,Email from contact where id=:contact.id];
    // reset the contact
    //contact = new Contact();
    return null;
  }

  // used by the visualforce page to send the link to the right dom element
  public string getFormTag() {
    return System.currentPageReference().getParameters().get('frm');
  }

  // used by the visualforce page to send the link to the right dom element for the text box
  public string getTextBox() {
    return System.currentPageReference().getParameters().get('txt');
  }
  }




Page
<apex:page controller="ContactLookupControl"
  title="Search"
  showHeader="false"
  sideBar="false"
  tabStyle="Contact"
  id="pg">
  <apex:form >
  <apex:outputPanel id="page" layout="block" style="margin:5px;padding:10px;padding-top:2px;">
  <apex:tabPanel switchType="client" selectedTab="name1" id="tabbedPanel">
    <!-- SEARCH TAB -->
      <apex:tab label="Search" name="tab1" id="tabOne"> 
      <apex:actionRegion > 
      <apex:outputPanel id="top" layout="block" style="margin:5px;padding:10px;padding-top:2px;">
        <apex:outputLabel value="Search" style="font-weight:Bold;padding-right:10px;" for="txtSearch"/>
        <apex:inputText id="txtSearch" value="{!searchString}" />
          <span style="padding-left:5px"><apex:commandButton id="btnGo" value="Go" action="{!Search}" rerender="searchResults"></apex:commandButton></span>
      </apex:outputPanel>
   
       <apex:outputPanel id="pnlSearchResults" style="margin:10px;height:350px;overflow-Y:auto;" layout="block">
        <apex:pageBlock id="searchResults">
          <apex:pageBlockTable value="{!results}" var="a" id="tblResults">
            <apex:column >
              <apex:facet name="header">
                <apex:outputPanel >Name</apex:outputPanel>
              </apex:facet>
               <apex:outputLink value="javascript:top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Id}','{!a.Name}', false);self.close();" rendered="{!NOT(ISNULL(a.Id))}">{!a.Name}</apex:outputLink>    
            </apex:column>
        <apex:column >
              <apex:facet name="header">
                <apex:outputPanel >Account Name</apex:outputPanel>
              </apex:facet>
               {!a.Account.Name}   
            </apex:column>
        <apex:column >
              <apex:facet name="header">
                <apex:outputPanel >Street</apex:outputPanel>
              </apex:facet>
               {!a.MailingStreet}   
            </apex:column>
  <apex:column >
              <apex:facet name="header">
                <apex:outputPanel >City</apex:outputPanel>
              </apex:facet>
               {!a.MailingCity}   
            </apex:column>
 <apex:column >
              <apex:facet name="header">
                <apex:outputPanel >State</apex:outputPanel>
              </apex:facet>
               {!a.MailingState}   
            </apex:column>
 <apex:column >
              <apex:facet name="header">
                <apex:outputPanel >Postal Code</apex:outputPanel>
              </apex:facet>
               {!a.MailingPostalCode}   
            </apex:column>
<apex:column >
              <apex:facet name="header">
                <apex:outputPanel >Phone</apex:outputPanel>
              </apex:facet>
               {!a.Phone}   
            </apex:column>
<apex:column >
              <apex:facet name="header">
                <apex:outputPanel >Email</apex:outputPanel>
              </apex:facet>
               {!a.Email}   
            </apex:column>
          </apex:pageBlockTable>
        </apex:pageBlock>
       </apex:outputPanel>
      </apex:actionRegion>
    </apex:tab>
    <!-- NEW CONTACT TAB -->
    <apex:tab label="New Contact" name="tab2" id="tabTwo">
        <apex:pageBlock id="newContact" title="New Contact" >
          <apex:pageBlockButtons >
            <apex:commandButton action="{!saveContact}" value="Save & Close"/>
          </apex:pageBlockButtons>
          <apex:pageMessages />
          <apex:pageBlockSection columns="2">
              <apex:inputField value="{!Contact.FirstName}"/>
              <apex:inputField value="{!Contact.LastName}"/>
              <apex:inputField value="{!Contact.AccountId}"/>
              <apex:inputField value="{!Contact.MailingStreet}"/>
              <apex:inputField value="{!Contact.MailingCity}"/>
              <apex:inputField value="{!Contact.MailingState}"/>
           <apex:inputField value="{!Contact.MailingPostalCode}"/>
           <apex:inputField value="{!Contact.MailingCountry}"/>
           <apex:inputField value="{!Contact.Phone}"/>
           <apex:inputField value="{!Contact.Email}"/>
          </apex:pageBlockSection>
        </apex:pageBlock>   
        <script>
        if({!Contact.id!=null}){
            //alert('{!Contact.Name} {!Contact.id}');
            top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!Contact.Id}','{!Contact.Name}', false);self.close();
        }
        </script>
    </apex:tab>
  </apex:tabPanel>
  </apex:outputPanel>
  </apex:form>
</apex:page>

Hope it helps.
Greetings, I currently only am able to achieve anywhere between 16-34% coverage with my current apex test class and am trying to determine ways to improve my apex class coverage.


Here is an instance of my apex class itself
 

APEX CLASS
public class ContactLookupControl {

  public Contact contact {get;set;} // new contact to create
  public List<Contact> results{get;set;} // search results
  public string searchString{get;set;} // search keyword

  public ContactLookupControl() {
    contact = new Contact();
    // get the current search string
    searchString = System.currentPageReference().getParameters().get('lksrch');
    runSearch();  
  }

  // performs the keyword search
  public PageReference search() {
    runSearch();
    return null;
  }

  // prepare the query and issue the search command
  private void runSearch() {
    // TODO prepare query string for complex serarches & prevent injections
    results = performSearch(searchString);               
  } 

  // run the search and return the records found. 
  private List<Contact> performSearch(string searchString) {

    String soql = 'select id, name from contact';
    if(searchString != '' && searchString != null)
      soql = soql +  ' where name LIKE \'%' + searchString +'%\'';
    soql = soql + ' limit 25';
    System.debug(soql);
    return database.query(soql); 

  }

  // save the new contact record
  public PageReference saveContact() {
    insert contact;
    // reset the contact
    contact = new Contact();
    return null;
  }

  // used by the visualforce page to send the link to the right dom element
  public string getFormTag() {
    return System.currentPageReference().getParameters().get('frm');
  }

  // used by the visualforce page to send the link to the right dom element for the text box
  public string getTextBox() {
    return System.currentPageReference().getParameters().get('txt');
  }

}


Here's the test class too

TEST CLASS

@isTest 
public class ContactLookupControlTest {
    static testMethod void validateContactLookupControl() {
        Contact c = new Contact();
            c.FirstName = 'Paul';
            c.LastName = 'Reid';
            c.MailingStreet = '205 Hill Street';
            c.MailingCity = 'Los Angeles';
            c.MailingState = 'CA';
            c.MailingPostalCode = '90015';
            c.Email = 'testingout1@aol.com';
            insert c;
    }
}

Are there any additional steps I can pursue to enable it to work accordingly. Let me know and hope it helps.
Greetings, I cannot seem to get this to work. I have my var set to cs, as it only works with that, rather, as I attempt to set it, I get the error message of var not set correctly. Please advise. Here's the code. The apex code appears correct.

<apex:page controller="NewCaseListController">
    <apex:form >
        <apex:pageBlock title="Case List" id="Case_list">
         <apex:repeat value="{!NewCases}" var="cs">
         <table style="width:1000px;">
          
<tr>
 <apex:repeat value="{!NewCases}" var="cs">
        <apex:outputLink value="https://na16.salesforce.com/{!cs.Id}">{!cs.CaseNumber}</apex:outputLink>
         <apex:outputLink value="{!cs.CaseNumber}">{!cs.CaseNumber}</apex:outputLink>
        </apex:repeat> 
             </tr>
        </table>
             </apex:repeat>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Greetings all, I seem to be stuck on the Use the Salesforce Lightning Design System to Style Visualforce Pages module, I modeled my contact page but can't seem to get the contact's to display, any steps others have taken?

Hi all, I am so close to finishing this process automation badge but am stuck in one area in Step 7.

I've built out my process builder as follows

User-added image
User-added image
User-added image

And my date formula as follows
 

Case(MOD(Date__c-DATE(1900,1,7),7),0,"Sunday",1,"Monday",2,"Tuesday",3,"Wednesday",4,"Thursday",5, "Friday",6,"Saturday", "")
 



Challenge Not yet complete... here's what's wrong:  The Robot Setup Day of the Week formula does not seem to be working properly. The Day of the Week should not fall on Saturday or Sunday. 

It works nicely but doesn't seem to pass, what could be up.
 

Greetings, I am working on the Salesforce Build a 3D Virtual Reality App project in trailhead and have downloaded Unity and Google's VR tools, but when I attempt to install the VR toolkit, I encounter this error?

Assets/Salesforce/Components/Scripts/Trigger.cs(24,51): error CS0246: The type or namespace name `GazeInputModule' could not be found. Are you missing an assembly reference?

Anything that I am missing.
Hi all, I am working on the Insecure Remote Site Trailhead and can't seem to get the image to display from a static resource zip file.

I am using this as my code
 
<apex:image url="{!URLFOR($Resource.Challenge_Resources,'Challenge_resources/Castle.png')}" />

Are there any steps I should take, hope it helps.
Hi all, I am stuck on the prevent SOQL injection trailhead, where I am looking to determine which portions of the code I would need to invoke escapeSingleQuotes or whitelist to enable. I've made several attempts at investigation to little avail. I have appended my code are there any steps I would need to take. My goal is to assess the code to see how it works and what I would need to do.

Hope it helps.
 
public class Prevent_SOQL_Injection_Challenge {

    public string textOne {get; set;}
    public string textTwo {get; set;}
    public string comparator {get; set;}
    public string numberOne {get; set;}

    public List<Supply__c> whereclause_records {get; set;}


    public PageReference stringSearchOne(){
        string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';
        string whereClause = '';

        if(textOne != null && textOne!=''){
                whereClause += 'name like  \'%'+textOne+'%\' ';
        }

        if(whereClause != ''){
            whereclause_records = database.query(query+' where '+whereClause+' Limit 10');
        }

        return null;
    }


    public PageReference stringSearchTwo(){
        string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';
        string whereClause = '';

        if(textTwo != null && textTwo!=''){
                whereClause += 'Storage_Location__r.name like  \'%'+textTwo+'%\' ';
        }

        if(whereClause != ''){
            whereclause_records = database.query(query+' where '+whereClause+' Limit 10');
        }

        return null;
    }


    public PageReference numberSearchOne(){
        string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';
        string whereClause = '';

        if(numberOne != null && comparator != null){
            whereClause += 'Quantity__c '+comparator+' '+numberOne+' ';
        }

        if(whereClause != ''){
            whereclause_records = database.query(query+' where '+whereClause+' Limit 10');
        }

        return null;
    }

}

 
Has anyone seen this error ? I am getting this when trying to add the report chart to the account page as part of the Challenge 7.

User-added image
I'm struggling with the custom lightning component on this part. I don't have much background coding and am having trouble finding resources to help me achieve coding the lightning component. If someone could help give me some framework code to create a custom lightning component to hold a URL or direct me to a resource that help break this down I'd be very appreciative.
 
I am facing another issue on this superbadge, specifically in Challenge #10, i am getting the following error:
The Campaign Influence Lightning report must have the correct 1. Aggregate, 2. Columns, 3. Groupings, and 4. Filter.

The requirements have no mention about what fields, groupings, filters, aggregates to include in the report. What am I missing?
Hello,
I'm fairly new to coding and I want to create a trigger where I share a document with a certain chatter group automatically and give them contributer rights when I upload a file via the chatter feed.This is how my trigger looks like:

trigger publishFileToGroup on ContentDocumentLink (after insert) {

  List<CollaborationGroup> chattergroup = [SELECT Id FROM CollaborationGroup WHERE Name = 'Apex Trigger Group'];  
  List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];

  ContentDocumentLink cdl = New ContentDocumentLink(
 
  LinkedEntityId = chattergroup[0].Id, ContentDocumentId = documents[0].Id, shareType = 'C');
 
  insert cdl;

}

This doesn't work and the following error message appears:
"Apex trigger publishFileToGroup caused an unexpected exception, contact your administrator: publishFileToGroup: execution of AfterInsert

caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, publishFileToGroup: execution of AfterInsert

caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Document with ID: 06958000000Aejh is already linked with the entity with ID: 0F9580000005tul: Linked Entity ID: [LinkedEntityId]

From my understanding it says that the document is already linked with the chatter group, which is not true. Any ideas?


 
I know that when an email bounces from a contact, a bounce reason and bounce date are populated, which prompt the 'Confirm Email Address' message to appear 

User-added image

Does anyone know of a way to modify this flag message? For example if i wanted to say 'Invalid Email Address' rather than 'Confirm Email Address'

Best,
Grant Ongstad

Hi all, I am so close to finishing this process automation badge but am stuck in one area in Step 7.

I've built out my process builder as follows

User-added image
User-added image
User-added image

And my date formula as follows
 

Case(MOD(Date__c-DATE(1900,1,7),7),0,"Sunday",1,"Monday",2,"Tuesday",3,"Wednesday",4,"Thursday",5, "Friday",6,"Saturday", "")
 



Challenge Not yet complete... here's what's wrong:  The Robot Setup Day of the Week formula does not seem to be working properly. The Day of the Week should not fall on Saturday or Sunday. 

It works nicely but doesn't seem to pass, what could be up.
 

There was an unhandled exception. Please reference ID: KLNTXAZY. Error: Faraday::ClientError. Message: MALFORMED_QUERY: When retrieving results with Metadata or FullName fields, the query qualificatio​ns must specify no more than one row for retrieval. Result size: 2

I have a flow that allows you to choose the product type, then the product, which creates the product, then asks if you want to add more products and goes back to the start. Seems to work perfectly. Not sure what this error is.

The call for service field description in the requirement is way different than what trailhead is actually validating.

User-added image
Hi,

I am stuck at the Create and Train the Dataset step on the Build a Cat Rescue App That Recognizes Cat Breeds Trailhead module.

I have successfully created the lightning component, uploaded the zip file and clicked on the train button but when I try to Verifiy I get the following error message:
"Challenge Not yet complete... here's what's wrong: 
Could not find a successful cat dataset training. The training may take a couple of minutes after the model is created."

Could you please advise ?

Thanks for your help.
Greetings, I am working on the Salesforce Build a 3D Virtual Reality App project in trailhead and have downloaded Unity and Google's VR tools, but when I attempt to install the VR toolkit, I encounter this error?

Assets/Salesforce/Components/Scripts/Trigger.cs(24,51): error CS0246: The type or namespace name `GazeInputModule' could not be found. Are you missing an assembly reference?

Anything that I am missing.
A Create a Record action for the Closed Won criteria node isn’t properly configured. Make sure that it creates a task and uses the same field settings as the ‘Follow up on new contract’ task action. Make sure that Due Date Only is set by using a formula.
User-added image

Hep me for this Problem!
I've been working on this trail for a bit - and while I undertsand the concepts, I'm stumped on why I'm getting this error: 
 
Challenge Not yet complete... here's what's wrong: 
A Create a Record action for the Closed Won criteria node isn't properly configured. Make sure that it creates a draft contract according to the instructions in the ‘Create contract for closed opportunity’ task action. Make sure that Start Date is set by using a formula.

I've gone over all of the workflow tasks information to recreate the contact. If I activate the process and close an opportunity, it creates a contract with the expected information and the date is 1mo away with 12mo term. The workflow's task (which is the template for the actual contract) specifies the following: 
 
Use the closed opportunity to create a contract for the associated account. 

Account: The account associated with this opportunity
Status: Draft
Contract Start Date: 1 month from today
Contract Term: 12
Here are my actions: 
User-added image

The Contract Start Date is set to the following formula:
DATE(
    YEAR(Today()) +
    FLOOR((1 + MONTH(Today())) / 12) -
    IF (MOD(MONTH(Today()) + 1, 12) = 0,
        1,
        0),

    MOD((1 + MONTH(Today()) - 1), 12) + 1,

    DAY(Today())
)

Again, for all practical purposes I'm passing this, as it functions and the contract is created. But I must be missing some small detail, named field, something that's tripping up the validation settings. Any help is appreciated!

 
Greetings, I've created my external object for the Data Integration Specalist Superbadge and have configured my external ID as seen below, however, the challenge seems to not pass, indicating that the indirect lookup was not properly created. Here's how I set up the projectRef__c field, which was what I used to push data from the external object into the project object in Salesforce. Are there any steps, I need to take. Hope it helps.
User-added image


User-added image