• KapavariVenkatramana
  • NEWBIE
  • 15 Points
  • Member since 2019
  • Salesforce Developer
  • Webgaints Softech Pvt Ltd.

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 2
    Likes Given
  • 7
    Questions
  • 21
    Replies
How to Wrap the Picklistvalues Within Table Column in PDF Visualforce Page.
1. Is it possible with CSS Style or
2.<apex:outputtext    componentselected picklist values are displayed inside this box only
 
trigger OppUpBsdOnStage on Opportunity (before update) {
    map<id,Opportunity> oppold= trigger.oldMap;
    map<id,Opportunity> oppnew= trigger.newMap;
    set<id> soi=oppold.keySet();
    for(id i:soi)
    {
        Opportunity oldop=oppold.get(i);
        Opportunity nwop=oppnew.get(i);
        if(oldop.StageName=='Closed Won'  &&  nwOp.StageName=='Closed Won')
        {
            nwop.closeDate=System.today();
            nwop.type='New Customer';
            oppnew.put(i, nwop);
        }

    }
    update oppnew.values();
}Trigger Error
The 'BusinessCard' Visualforce page wasn't found.

ChallengeMy code is like that User-added image
Solution to Use Mocks and Stub Objects


YOUR CHALLENGE
Write tests using mocks and stubs
Not every call to a third party service succeeds. So, we need to test both success and failure responses. Write a unit test to cover the ExternalSearch classes’ handling of response codes higher than 200.
Add a unit test method to ExternalSearch_tests.cls that uses the HTTPMockFactory class to return a 500 response
Make sure you have 100% code coverage on the ExternalSearch class
 
Please Solution needed to 
Unit Testing on the Lightning Platform 
Write Permission-Based Tests

YOUR CHALLENGE
Create a permission-based test
Create a Custom User profile in your Trailhead Playground and give it View All permission on Private_object__c records. Write a positive permission test demonstrating that users with the Custom User profile can view records that they don’t own. 
To get started
In Setup, clone the Custom: Support Profile profile and name it ‘Custom User’.
Give the Custom User profile View All permissions on the custom object Private_Object__c. (Listed as Private Objects in the user interface)
Create a new test class named PositivePermission_tests
Write a positive permission unit test showing that users with the Custom User profile can access Private_Object__c records that they do not own
Execute your unit tests and ensure that they all pass
how to write 100% test class for Calculator CLass. Unit Testing on the Lightning Platform  Write Negative Tests
send an email to all accounts owners to provide infomrtaion
Create a SFDC Batch Process and test Class
1.        Send email to all Account Owners
        Account Name
2.            Total Number of Opportunities
3.            Nmber of Opportunities having amount greater than 50,000
4.            Total number of Closed won lost Opportunites
Email Notification after finish Method
Schedule batch Process to run over the Friday 7
 
Please Solution needed to 
Unit Testing on the Lightning Platform 
Write Permission-Based Tests

YOUR CHALLENGE
Create a permission-based test
Create a Custom User profile in your Trailhead Playground and give it View All permission on Private_object__c records. Write a positive permission test demonstrating that users with the Custom User profile can view records that they don’t own. 
To get started
In Setup, clone the Custom: Support Profile profile and name it ‘Custom User’.
Give the Custom User profile View All permissions on the custom object Private_Object__c. (Listed as Private Objects in the user interface)
Create a new test class named PositivePermission_tests
Write a positive permission unit test showing that users with the Custom User profile can access Private_Object__c records that they do not own
Execute your unit tests and ensure that they all pass
how to write 100% test class for Calculator CLass. Unit Testing on the Lightning Platform  Write Negative Tests
can somebody help on this. i finished all the other ones in this trail head. installed the package. first ine worked fine. 
challenge is : 
Edit the AllBadThings() method, as follows:
Replace the if statement with a Where clause
Move the update statement outside of the for loop
Rename the method AllGoodThings()
i changed as below
public class TrailLoop {      
       public static void AllGoodThings(Account a) {
        List<Task> allMyTasks = [Select Id, status, whatId From Task Where whatId = :a.id];
        for (Task t : allMyTasks) {
                            {
                t.status = 'Completed';
                }
            update allMyTasks;
        }
    }
but it is failing with this error

 
I seem to be stuck on this trailhead module or write negative tests unit, while I have 93 percent code coverage, I can't seem to get the code coverage to hit 100 percent at the "returnValue" piece doesn't seem to hit.
My code is as follows.

Calculator Class
 
public class Calculator {
 public class CalculatorException extends Exception{}

  public static Integer addition(Integer a, Integer b){
   return a + b;
    }

   public static Integer subtraction(Integer a, Integer b){
    return a - b;
    }

 public static Integer multiply(Integer a, Integer b){
  if(b==0 || a==0){
  throw new CalculatorException('It doesn\'t make sense to multiply by 
   zero');
  }
  return a * b;
  }

 public static Decimal divide(Integer numerator, Integer denominator){
  if(denominator == 0){
  throw new CalculatorException('you still can\'t divide by zero');
   }
 Decimal returnValue = numerator / denominator;
  if(returnValue < 0){
    throw new CalculatorException('Division returned a negative value.' + 
 returnValue);
 }
   return returnValue;
  }


 }

And my test class as follows
 
@isTest
   public class Calculator_Tests {

@isTest
 public static void addition() {
    Calculator.addition(1, 0);
   }
@isTest
  public static void subtraction() {
    Calculator.subtraction(1, 0);
   }

@isTest
 public static void divide_throws_exception_for_division_by_zero() {
 Boolean caught = false;
 try {
    Calculator.divide(1, 0);
  } catch (Calculator.CalculatorException e) {
    System.assertEquals('you still can\'t divide by zero', e.getMessage(), 
  'caught the right exception');
    caught = true;
   }
   System.assert(caught, 'threw expected exception');
   }

  @isTest
 public static void divide_throws_exception_for_division_by_two() {
 Boolean caught = true;
 try {
    Calculator.divide(1, 2);
 } catch (Calculator.CalculatorException e) {
    System.assertEquals('you still can\'t divide by zero', e.getMessage(), 
  'caught the right exception');
    caught = true;
   }
   System.assert(caught, 'threw expected exception');
 }


@isTest
public static void multiply_by_one() {
  Boolean caught = false;
  try {
    Calculator.multiply(1, 0);
    } catch (Calculator.CalculatorException e) {
    System.assertEquals('It doesn\'t make sense to multiply by zero', 
    e.getMessage(), 'caught the right exception');
     caught = true;
    }
    System.assert(caught, 'threw expected exception');
  }

@isTest
 public static void multiply_by_two() {
  Boolean caught = true;
  try {
     Calculator.multiply(1, 2);
   } catch (Calculator.CalculatorException e) {
    System.assertEquals('It doesn\'t make sense to multiply by zero', 
  e.getMessage(), 'caught the right exception');
    caught = true;
   }
   System.assert(caught, 'threw expected exception');
}   
}

 
Hello,
Can someone help me with module Metadata API, unit Build Admin Tools for Automated Configuration Changes?

The error I'm getting is:
Line 12: Method does not exist or incorrect signature; void add(Metadata.CustomMetadataValue) from the type List

Below is my code:
public class MetadataExample {

    public void updateMetadata () {
        Metadata.CustomMetadata customMetadata = new Metadata.CustomMetadata();
        customMetadata.fullName = 'MyNamespace__MyMetadataTypeName.MyMetadataRecordName';
        
        Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue();
        customField.field = 'customField__c';
        customField.value = 'New value';
        
        List <Metadata.CustomMetadata> mdtlist = new List<Metadata.CustomMetadata>();
        mdtlist.add(customField);  // Line 12
    }

}

I feel like I'm missing something very basic but I can't find any documentation specific to what I'm trying to do and the challenge is not similar (to me) to the example. Can someone please explain where I went wrong?
I'm trying to complete the trail module named in the subject, but I'm getting an error of:
Challenge Not yet complete... here's what's wrong: 
Couldn't find newField.behavior set to 'Metadata.UiBehavior.Edit', or newField.field set to 'AMAPI__Apex_MD_API_Twitter_name__c' or method doesn't return 'layoutMetadata'. Please double-check the instructions

Everything looks right to me in the class.  I can't use the namespace they provide because it's already taken.   Earlier in the exercise, it tells you to use your own namespace which I've done.  Can anyone see what's wrong?
 
public class UpdateContactPageLayout {
    // Add custom field to page layout
    
    public Metadata.Layout addLayoutItem () {
        
        // Retrieve Contact layout and section 
        List<Metadata.Metadata> layoutsList = 
            Metadata.Operations.retrieve(Metadata.MetadataType.Layout, 
            new List<String> {'Contact-Contact Layout'});
        Metadata.Layout layoutMetadata = (Metadata.Layout) layoutsList.get(0);
        Metadata.LayoutSection contactLayoutSection = null;
        List<Metadata.LayoutSection> layoutSections = layoutMetadata.layoutSections;
        for (Metadata.LayoutSection section : layoutSections) {
            
            if (System.equals(section.label, 'Additional Information')) {
                contactLayoutSection = section;
                break;
            }
        }
        
        // Add the field under Contact info section in the left column
        List<Metadata.LayoutColumn> contactColumns = contactLayoutSection.layoutColumns;     
        List<Metadata.LayoutItem> contactLayoutItems = contactColumns.get(0).layoutItems;
        
        // Create a new layout item for the custom field
        Metadata.LayoutItem newField = new Metadata.LayoutItem();
        newField.behavior = Metadata.UiBehavior.Edit;
        newField.field = 'BOBN_TRAILHEAD__Apex_MD_API_Twitter_name__c';
        contactLayoutItems.add(newField);
        
        return layoutMetadata;
    }
}

 
Hello everyone,

The challenge is the following :
 
Create a Service and Implement a Caller.
Create an Apex class that is a service that exposes a bulkified service method. The service closes and sets the reason for one or more given case records. Implement an Apex REST class that calls this service.
  • Create an Apex class called CaseService that contains a void static method called closeCases that takes a set of Case IDs and a String parameter for the close reason.
  • Create a REST Apex class called CaseCloseResource with a URL mapping /case/*/close (where * will be the Id). Implement a POST closeCase method which accepts a String reason and calls the CaseService.closeCases service method passing in the Id and close reason.
I keep getting the following error when trying to submit my solution on "Apply Service Layer Principles in Apex"
Challenge Not yet complete... here's what's wrong: 
The Apex service does not appear to be closing cases correctly with the specified reason.

My Service class is the following:
 
global with sharing class CaseService {

    global static void closeCases(List<Id> caseIds, String closingReason) {
        if (caseIds == null || caseIds.size() == 0) {
            throw new CaseServiceException('You should tell me which cases you wanna close');
        }
        
        if (closingReason == null || closingReason == '') {
            throw new CaseServiceException('I won\'t close a case without any reason');
        }
        
        List<Case> closedCases = new List<Case>();
        
        for(Id caseId : caseIds) {
            Case caseToClose = new Case(
            	Id = caseId,
                Status = 'Closed',
                Reason = closingReason
            );
            closedCases.add(caseToClose);
        }
        
        SavePoint sp = Database.setSavepoint();
        if (closedCases.size() > 0) {
            try {
                update closedCases;
            } catch (Exception e) {
                Database.rollback(sp);
                throw e;
            }
        }
    }
    
    public class CaseServiceException extends Exception {}
}

And my webservice endpoint (I can't really call it restful) is :
 
@RestResource(urlMapping='/case/*/close')
global with sharing class CaseCloseResource {
    
    @HttpPost
    global static void closeCase(String reason) {                
        Id id = RestContext.request.requestURI.substringBetween('case/', '/close');
        CaseService.closeCases(new Id[]{id}, reason);
    }
}

I tried in an anonymous code execution :
 
Id id = '5000Y000002Vc8Y';
CaseService.closeCases(new Id[]{id}, 'You shall be closed!');
And successfully got the following : 
Changed Case Reason from Installation to You shall be closed!.
Changed Status from New to Closed.

Then, using workbeng, I tried the following request :
POST /services/apexrest/case/5000Y000002Vc8m/close
Payload : {"reason" : "Please close this case too!"}

And got a 200 response from the server as well as 
Changed Case Reason from Feedback to Please close this case too!.
Changed Status from New to Closed.

That's why I am still confused on why the challenge checker is rejecting me ?
Did I miss something the challenge requested me to do ?
 
Challenge Not yet complete... here's what's wrong: 
Could not find an account named 'Blackbeards Grog Emporium' created from Workbench with the Description 'The finest grog in the seven seas.'

I have created it twice: (I have to use localhost/workbench MAMP due to my company security policy)
User-added image
User-added image
User-added image
User-added image


 
Hi All,

I receive the following error when attempting to check the challenge for Apply Unit of Work

Challenge Not yet complete... here's what's wrong: 
The 'challangeComplete' method in the 'UnitOfWorkTest' class has not successfully passed all tests. Ensure that you run the tests and it passes successfully before attempting this challenge again.

However, when I run my code in Developer Console, my test passes.  Any ideas on the problem?  Here is the code:

@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.commitWork();
 
        fflib_SObjectUnitOfWork uow2 = new fflib_SObjectUnitOfWork(
            new Schema.SObjectType[]{
                Account.SObjectType,
                Contact.SObjectType,
                Note.SObjectType
            }
        );        
        for (Account a : [SELECT Id, Name, (SELECT Id, LastName FROM Contacts), (SELECT Id, ParentId, Title, Body FROM Notes) FROM Account]) {
            a.Name = 'Test';
            uow2.registerDirty(a);
            
            Integer i = 0;
            for (Contact c : a.Contacts) {
                c.LastName = 'Test';
                uow2.registerDirty(c);
                
                a.Notes[i].Body='Test';
                uow2.registerDirty(a.Notes[i]);
                i++;
            }
        }        
        
        test.startTest();
        uow2.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,

I can't pass the challenge (https://developer.salesforce.com/trailhead/force_com_dev_intermediate/lex_dev_lc_basics/lex_dev_lc_basics_events). This is the error when check challenge:

Challenge Not yet complete... here's what's wrong: 
The campingList JavaScript controller isn't adding the new record to the 'items' value provider.


I tryed in the browser add new Camping Items and it's working correctly. The item is added to database and the list is updated.

This is my code:

campingList Component
<aura:component controller="CampingListController">
    
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    <aura:handler name="addItem" event="c:addItemEvent" action="{!c.handleAddItem}"/>
    
    <div class="slds-page-header" role="banner">

      <div class="slds-grid">

        <div class="slds-col">

          <p class="slds-text-heading--label">Camping Items</p>

          <h1 class="slds-text-heading--medium">My Camping Items</h1>

        </div>

      </div>

    </div>

      
  <div aria-labelledby="newitemform">

      <fieldset class="slds-box slds-theme--default slds-container--small">
    
        <c:campingListForm />
    
      </fieldset>

	</div>
    
    
     <aura:attribute name="items" type="Camping_Item__c[]"/>

    <div class="slds-card slds-p-top--medium">
        <header class="slds-card__header">
            <h3 class="slds-text-heading--small">Camping List Items</h3>
        </header>
        
        <section class="slds-card__body">
            <div id="list" class="row">
                <aura:iteration items="{!v.items}" var="campItem">
                    <c:campingListItem item="{!campItem}"/>
                </aura:iteration>
            </div>
        </section>
    </div>

</aura:component>

campingList Controller.js
({
    
    doInit: function(component, event, helper) {
    
        var action = component.get("c.getItems");
    
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.items", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
    
        $A.enqueueAction(action);
    },    
    
    handleAddItem: function(component, event, helper) {
        var item = event.getParam("item");
                
        var action = component.get("c.saveItem");
        action.setParams({
            "item": item
        });
        
        action.setCallback(this, function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {        
                var theItems = component.get("v.items");
                theItems.push(item);
                component.set("v.items",theItems);
            }
        });
        $A.enqueueAction(action);
    }
    
})

CampingListController
public with sharing class CampingListController {

    @AuraEnabled 
    public static List<Camping_Item__c> getItems() {
        return [SELECT Id, Name, Price__c, Quantity__c, Packed__c FROM Camping_Item__c];
    }
    
    @AuraEnabled
    public static Camping_Item__c saveItem(Camping_Item__c item) {
        upsert item;
        return item;
    }
}

CampingListForm Component
<aura:component >
    
     <aura:attribute name="newItem" type="Camping_Item__c"
     default="{ 'sobjectType': 'Camping_Item__c',
                    'Name': '',
                    'Packed__c': false,
                    'Price__c': '0',
                    'Quantity__c': '0' }"/>
	<aura:registerEvent name="addItem" type="c:addItemEvent"/>
    
  <div aria-labelledby="newitemform">
      <fieldset class="slds-box slds-theme--default slds-container--small">
    
        <legend id="newitemform" class="slds-text-heading--small 
          slds-p-vertical--medium">
          Add Camping Item
        </legend>
    
        <form class="slds-form--stacked">
    
          <div class="slds-form-element slds-is-required">
              <div class="slds-form-element__control">
                  <ui:inputText aura:id="name" label="Camping Item Name"
                      class="slds-input"
                      labelClass="slds-form-element__label"
                      value="{!v.newItem.Name}"
                      required="true"/>
              </div>
         </div>
            
          <div class="slds-form-element">
              <ui:inputCheckbox aura:id="packed" label="Packed?"
                  class="slds-checkbox"
                  labelClass="slds-form-element__label"
                  value="{!v.newItem.Packed__c}"/>
          </div>
            
        <div class="slds-form-element">
              <div class="slds-form-element__control">
                  <ui:inputCurrency aura:id="price" label="Price"
                      class="slds-input"
                      labelClass="slds-form-element__label"
                      value="{!v.newItem.Price__c}" />
    
              </div>
          </div>
    
         <div class="slds-form-element">
              <div class="slds-form-element__control">
                  <ui:inputNumber aura:id="quantity" label="Quantity"
                      class="slds-input"
                      labelClass="slds-form-element__label"
                      value="{!v.newItem.Quantity__c}"/>
    
              </div>
          </div>
    
          <div class="slds-form-element">
              <ui:button label="Create Camping Item"
                  class="slds-button slds-button--brand"
                  press="{!c.clickCreateCampingItem}"/>
          </div>
    
        </form>
    
      </fieldset>
</div>

</aura:component>

CampingListForm Controller.js
({    
    
    clickCreateCampingItem : function(component, event, helper) {
        
        var validCamping = true;

        // Name must not be blank
        var nameField = component.find("name");
        var expname = nameField.get("v.value");
        if ($A.util.isEmpty(expname)){
            validCamping = false;
            nameField.set("v.errors", [{message:"Camping Item name can't be blank."}]);
        }
        else {
            nameField.set("v.errors", null);
        }

        
        var priceField = component.find("price");
        var price = priceField.get("v.value");
        if ($A.util.isEmpty(price) || isNaN(price) || (price <= 0.0)){
            validCamping = false;
            priceField.set("v.errors", [{message:"Camping Item price can't be blank."}]);
        }
        else {
            priceField.set("v.errors", null);
        }
        
        var quantityField = component.find("quantity");
        var quantity = quantityField.get("v.value");
        if ($A.util.isEmpty(quantity) || isNaN(quantity) || (quantity <= 0)){
            validCamping = false;
            quantityField.set("v.errors", [{message:"Camping Item quantity can't be blank."}]);
        }
        else {
            quantityField.set("v.errors", null);
        }

        if(validCamping){
            
            helper.createItem(component);
            
        }
        
    },
})

CampingListForm Helper.js
({
    
     createItem : function(component) {
        var newItem = component.get("v.newItem");
        var addEvent = component.getEvent("addItem");
        addEvent.setParams({"item" : newItem});
        addEvent.fire();
        component.set("v.newItem",
                     { 'sobjectType': 'Camping_Item__c',
                    'Name': '',
                    'Packed__c': false,
                    'Price__c': 0,
                    'Quantity__c': 0});
    }
})

Could anyone help me?

Thanks,
Regards.
Hello! 
I have a problem ... 
"Challenge Not yet complete... here's what's wrong: 
The 'Phone__x' external object is not correctly setup with an indirect relationship to the User standard object."
In my opinion I do everything alright ... 
I will show everything what I am doing step-by-step, and maybe somebody help me with this issue :)
1. Creating an OData 2.0 external data source with 'Mobile Devices' as the label
2. Validate and Syncing 
3. Changing APIs from phones__x to phone__x.
4. Adding phones tab.
5. Creating User Custom Field Phone UUID with full visibility
6. Editing phone__x UUID field and adding indirect lookout relationship -> user -> phone_uuid__c, visible for all
7. Adding value '0000123442' for 'Phone_UUID__c' field.

CHECKING
"Challenge Not yet complete... here's what's wrong: 
The 'Phone__x' external object is not correctly setup with an indirect relationship to the User standard object."

8. Soo I am trying to check my phones tab, I read somewhere about empty fields there... 
8a. First is empty...
8b. Last got something...
9. Now I am changing value for 'Phone_UUID__c' field again and typing default value as '44'

CHECKING AGAIN
"Challenge Not yet complete... here's what's wrong: 
The 'Phone__x' external object is not correctly setup with an indirect relationship to the User standard object."

10. In somebody solve I find value of phone external ID, so ... lets try with ID, which is not empty
10a. Adding 'NTczMWJmZTNmODZjMmMwMzAwZDM4ZDBk' as value for 'Phone_UUID__c' field.

AND ??? ...

Challenge Not yet complete... here's what's wrong: 
The 'Phone__x' external object is not correctly setup with an indirect relationship to the User standard object.

Any ideas ? :)
I am having issues with Creating  an Apex class that returns Account objects for the Mapping.net concepts challenge.  I am a VB and Javascript programmer and I can't seem to get the syntax right.   
public class AccountUtils {
    
    public static void accountsByState(String st){
       List<String> accts = [SELECT Id, Name FROM Account WHERE billingState = :st];
 }
  
}
I believe the first part is correct, but I cannot seem to get a return value.  I am confused by the constructors.  I have tried the documentation but I can't get a return value.  Please help.  I need to get this challenge complete.
 
Here is the Question


Create an Apex class that implements the Schedulable interface to update Lead records with a specific LeadSource. Write unit tests that achieve 100% code coverage for the class. This is very similar to what you did for Batch Apex.
Create an Apex class called 'DailyLeadProcessor' that uses the Schedulable interface.
The execute method must find the first 200 Leads with a blank LeadSource field and update them with the LeadSource value of 'Dreamforce'.
Create an Apex test class called 'DailyLeadProcessorTest'.
In the test class, insert 200 Lead records, schedule the DailyLeadProcessor class to run and test that all Lead records were updated correctly.
The unit tests must cover all lines of code included in the DailyLeadProcessor class, resulting in 100% code coverage.
Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.


Here is my code so far

global class DailyLeadProcessor implements Schedulable {

    global void execute(SchedulableContext ctx) {
        list<leads>Lead = [select leadSource from lead where isnull= true]
        
         for (Integer i = 0; i < 200; i++) {
            Leads.add(new lead(
                name='Dream force'+i
            ));
        }
        insert Leads;
    }

I am not sure what is wrong here
Hello everyone I could use some help on the using future Methods trailhead. Please keep in mind I am not an Apex coder at all but I am trying to learn as much as I can.

Here is the Task

Create an Apex class with a method using the @future annotation that accepts a List of Account IDs and updates a custom field on the Account object with the number of contacts associated to the Account. Write unit tests that achieve 100% code coverage for the class.
Create a field on the Account object called 'Number_of_Contacts__c' of type Number. This field will hold the total number of Contacts for the Account.
Create an Apex class called 'AccountProcessor' that contains a 'countContacts' method that accepts a List of Account IDs. This method must use the @future annotation.
For each Account ID passed to the method, count the number of Contact records associated to it and update the 'Number_of_Contacts__c' field with this value.
Create an Apex test class called 'AccountProcessorTest'.
The unit tests must cover all lines of code included in the AccountProcessor class, resulting in 100% code coverage.
Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.

I have written an Apex class and a Test class but I think I am doing them both Wrong: because when I try to check the challenge i Get this error

Challenge Not yet complete... here's what's wrong: 
The 'AccountProcessorTest' test class doesn't appear to be calling the 'AccountProcessor.countContacts' method between Test.startTest() and Test.stopTest().


When I run the Test class I get this error :

System.QueryException: List has no rows for assignment to SObject

Here is the CLASS:
 
public class AccountProcessor {
     @future

  public static void someFutureMethod(List<id> scope) {

   Account[] updates = new Account[] {};
        for (AggregateResult ar : [
                select AccountId a, count(Id) c
                from Contact
                where AccountId in :scope
                group by AccountId
                ]) {
            updates.add(new Account(
                    Id = (Id) ar.get('a'),
                    Number_of_Contacts__c = (Decimal) ar.get('c')
                    ));
        }
        update updates;
    }

}

Here is the Test Class:
 
@IsTest
public class AccountProcessorTest {
  public static testmethod void TestAccountProcessorTest() {
 
Test.startTest();
     Account a = new Account();
        a.Name = 'Test Account';
        Insert a;
      
      Contact cont = New Contact();
      
      cont.FirstName ='Bob';
      cont.LastName ='Masters';
      cont.AccountId = a.Id;
      Insert cont;

    Test.stopTest() ;
     Contact ACC = [select AccountId from Contact where id = :a.id LIMIT 1];

 
        System.assert(Cont.AccountId != null);
        System.assertequals(cont.id, ACC.AccountId);

  }}

I have used alot or diffrent google searches to get me this far. But I have not Idea if Im even remotly close to the right answer or not.


 
i have created
1.AnimalLocator User-added image



2.AnimalLocatorMock
User-added image

3.AnimalLocatorTest

User-added image


error i am getting

User-added image

please help me
Hi all,

I'm stuck in the Apex Integration Services - Apex SOAP Callouts challenge with the following message "The Apex class 'ParkLocator' does not appear to be calling the SOAP endpoint.".

Could you please advise ?
I am trying to complete the challenge of the Integrating External Data challenge, and am hitting an 'interesting' problem.  I believe I've gone through all the steps correctly, but an getting the error below:

The 'Phone__x' external object is not correctly setup with an indirect relationship to the User standard object.

When I go do External Objects/phones/edit UUID I can see the UUID field definition.  I have numerous times clicked on Change FIeld Type/Indirect Lookup Relationship/Related to User/Target Field Phone_UUID__c/Next/Save.  Each time I go though that when I get to the Target Field value the value is set to --None--.  It's acting like it forgets that I gave it a value.  That would explain the error message

Any ideas as to how I can get around this?

Thanks
hi
i am new to salesforce platform.
Install a simple Apex class, write unit tests that achieve 100% code coverage for the class, and run your Apex tests.The Apex class to test is called 'VerifyDate', and the code is available here. Copy and paste this class into your Developer Edition via the Developer Console.
'VerifyDate' is a class which tests if a date is within a proper range, and if not will return a date that occurs at the end of the month within the range.
The unit tests must be in a separate test class called 'TestVerifyDate'.
The unit tests must cover scenarios for all lines of code included in the Apex class, resulting in 100% code coverage.
Run your test class at least once (via the Developer Console) before attempting to verify this challenge.

In the above challege i am not able to write a 'TestVerifyDate' class. I dont unsertstand how to write it for a date.
plz help..
I am stuck up with this challenge in Visualforce mobile module,Where in i need to use Visualforce page that must display the assistant's phone number using a 'tel:' hyperlink. am getting the above error

I have created HelloWorld example class in developer console which is in apex work book


public class HelloWorld{
    public static void sayYou(){
        System.debug('you');
    }
     
    public void sayMe(){
    System.debug('Me');
    }
}


I think I have created top - level class and declared static method and instance method in that class.

But when I execute this class I am getting error saying that 'Only top-level class methods can be declared static'

Please help me if there is any wrong in my example. 
 
I am new to apex code.I think it is silly doubt but please help me.
I know I have completed the challenge correctly but keep getting this error. Note that the challenge has you create a "custom" object, not a "customer" object as stated in the error. I would like my 500 pts, please. :-)
I'm trying to complete the trail module named in the subject, but I'm getting an error of:
Challenge Not yet complete... here's what's wrong: 
Couldn't find newField.behavior set to 'Metadata.UiBehavior.Edit', or newField.field set to 'AMAPI__Apex_MD_API_Twitter_name__c' or method doesn't return 'layoutMetadata'. Please double-check the instructions

Everything looks right to me in the class.  I can't use the namespace they provide because it's already taken.   Earlier in the exercise, it tells you to use your own namespace which I've done.  Can anyone see what's wrong?
 
public class UpdateContactPageLayout {
    // Add custom field to page layout
    
    public Metadata.Layout addLayoutItem () {
        
        // Retrieve Contact layout and section 
        List<Metadata.Metadata> layoutsList = 
            Metadata.Operations.retrieve(Metadata.MetadataType.Layout, 
            new List<String> {'Contact-Contact Layout'});
        Metadata.Layout layoutMetadata = (Metadata.Layout) layoutsList.get(0);
        Metadata.LayoutSection contactLayoutSection = null;
        List<Metadata.LayoutSection> layoutSections = layoutMetadata.layoutSections;
        for (Metadata.LayoutSection section : layoutSections) {
            
            if (System.equals(section.label, 'Additional Information')) {
                contactLayoutSection = section;
                break;
            }
        }
        
        // Add the field under Contact info section in the left column
        List<Metadata.LayoutColumn> contactColumns = contactLayoutSection.layoutColumns;     
        List<Metadata.LayoutItem> contactLayoutItems = contactColumns.get(0).layoutItems;
        
        // Create a new layout item for the custom field
        Metadata.LayoutItem newField = new Metadata.LayoutItem();
        newField.behavior = Metadata.UiBehavior.Edit;
        newField.field = 'BOBN_TRAILHEAD__Apex_MD_API_Twitter_name__c';
        contactLayoutItems.add(newField);
        
        return layoutMetadata;
    }
}