• Aslam Chaudhary
  • NEWBIE
  • 392 Points
  • Member since 2017
  • SaharaSys

  • Chatter
    Feed
  • 13
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 1
    Questions
  • 71
    Replies
/*********************************************************************

* Description - Apex REST service with GET and POST methods

* Author - AP

<u>Json format</u>

{

"name" : "Akash",

"phone" : "8826031286",

"website" : "www.akashmishra.co.in"

}

***********************************************************************/

@RestResource(urlMapping='/v3/accounts/*')

global with sharing class REST_AccountService_V4 {

@HttpPost

global static AccountWrapper doPost(String name, String phone, String website) {

RestRequest req = RestContext.request;

RestResponse res = RestContext.response;

AccountWrapper response = new AccountWrapper();

Account acct = new Account();

acct.Name = name;

acct.Phone = phone;

acct.Website = website;

insert acct;

response.acctList.add(acct);

response.status = 'Success';

response.message = 'Your Account was created successfully.';

return response;

}

@HttpGet

global static AccountWrapper doGet() {

RestRequest req = RestContext.request;

RestResponse res = RestContext.response;

AccountWrapper response = new AccountWrapper();

String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

if(doSearch(accountId))

{

searchAccounts(req, res, response);

}

else

{

findAccount(res, response, accountId);

}

return response;

}

// If the item to the right of the last forward slash is "accounts", the request went to

//v3/accounts?Name=Akash

// Else the request went to v3/accounts/&lt;something&gt;, which is not a search, but a specific

//entity

private static boolean doSearch(String accountId) {

if(accountId == 'accounts') {

return true;

}

return false;

}

//If the request came to /v3/accounts, then we want to execute a search

Public static void searchAccounts(RestRequest req, RestResponse res,

AccountWrapper response) {

//Use the RestRequest's params to fetch the Name parameter

String searchTerm = req.params.get('Name');

if(searchTerm == null || searchTerm == '') {

response.status = 'Error';

response.message = 'You must provide a Name for your search term.';

res.StatusCode = 400;

}

else {

String searchText = '%'+searchTerm+'%';

List&lt;Account&gt; searchResults =

[SELECT Id, Name, Phone, Website FROM Account WHERE Name LIKE : searchText];

if(searchResults != null &amp;&amp; searchResults.size() &gt; 0) {

response.acctList = searchResults;

response.status = 'Success';

response.message = searchResults.size()

+ ' Accounts were found that matched your search term.';

}

else {

response.status = 'Error';

response.message =

'No Accounts were found based on that Name, please search again.';

}

}

}

&nbsp;

//If the request came to v3/accounts/sometext then we want

//to find a specific account

Public static void findAccount(RestResponse res, AccountWrapper response,

String accountId) {

// Provided we recevied an External Id, perform the search and return the results

if(accountId != null &amp;&amp; accountId != '') {

List&lt;Account&gt; result = [SELECT Id, Name, Phone, Website FROM Account

WHERE External_Id__c =: accountId];

if(result != null &amp;&amp; result.size() &gt; 0) {

response.acctList.add(result[0]);

response.status = 'Success';

}

else {

response.status = 'Error';

response.message = 'This account could not be found, please try again.';

res.StatusCode = 404;

}

}

// If the request came to /v3/accounts/ (without an Account Id),

//return an error

else {

response.status = 'Error';

response.message = 'You must specify an External Id.';

res.StatusCode = 400;

}

}

global class AccountWrapper {

public List&lt;Account&gt; acctList;

public String status;

public String message;

public AccountWrapper(){

acctList = new List&lt;Account&gt;();

}

}

}



can anybody resolve this issue
 
I have a Code in which i am using apex:inputField for lookup field. when i am getting this field value in script it gives me the name of the record selected.
I want to get the ID of the record selected either in javascript variable or in apex controller.
Page------------------------------->>

<apex:page Controller="ApexParamController">
    <script>
    function fire(){
        var fr=document.getElementById('{!$Component.frm.acc}').value;
        alert('test:: '+fr);
    }
    </script>
    <apex:form id="frm">
        <apex:inputfield value="{!contact.AccountId}" id="acc"/>
        <apex:commandButton onclick="fire();" value="Save" action="{!print}" />
    </apex:form>
</apex:page>
 
Class------------------->>

public class ApexParamController {
    Public Contact contact{get;set;}
    public void print(){
        contact = new Contact();
        system.debug('Account::'+contact.AccountID);
    }
}

 
Hi folks, 

This seems like a weird one (must be dead simple, but not seeing it).

I'm simply trying to access an Http response header key value as specified in the docs, When I try to save, the compiler is complaining about the method signature. I've tried in a few different orgs to make sure somehow the HttpResponse class hadn't been overridden somehow...

Thanks for any clues/suggestions.
public class HttpTesting {
    public HttpTesting() {
        String aString = 'aHeaderKey';
        HttpRequest anHttpRequest = new HttpRequest();
		HttpResponse anHttpResponse = new Http().send(anHttpRequest);

        System.debug('---> anHttpResponse.getHeaderKeys(): ' + anHttpResponse.getHeaderKeys());
        System.debug('---> anHttpResponse.getHeaderKey(aString): ' + anHttpResponse.getHeaderKey(aString));  // <--- 'Method does not exist or incorrect signature: void getHeaderKey(String) from the type System.HttpResponse'
    }
}

 
  • January 14, 2018
  • Like
  • 0
I have a controller extension for a custom create child object page to take me back to the correct page after editing and to allow me to have an erorr message wthout using a validation. The controller works exactly as it should but I am having issues writing the test class for it. Iget the error "system.queryexception: list has no rows for assignment to sobject" My code is as below:
Controller:
public with sharing class createController {
	public String oppId {get;set;}
	public Opportunity opp;
	public Opportunity_Forecast__c oppf {get;set;}
	private ApexPages.StandardController stdController; 
	
    public createController(ApexPages.StandardController stdController) {
    	this.stdController = stdController;
        oppf = (Opportunity_Forecast__c)stdController.getRecord();
        String oppid = (oppf.Opportunity__c);
        String ID = ApexPages.currentPage().getParameters().get('oppid');
        opp = [select Automatic_Forecasting__c from Opportunity where Id =:ID]; 
        if (ID != null){
        	oppf.Opportunity__c= ID;   
        }   
    }
	
	public PageReference cancelAndReturn() 
    {
    	PageReference cancel = new PageReference('/' + ApexPages.currentPage().getParameters().get('oppid'));
        cancel.setRedirect(true);
 		return cancel;	
    }
	
	public PageReference saveAndReturn()
    {
        try{
        	if(opp.Automatic_Forecasting__c == true){
        		ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: Upside Automation must be disabled on the opportunity page before editing forecasts.');
        		ApexPages.addMessage(myMsg);
        		return null;
        	}
        	else{
        		upsert oppf;
        		PageReference save = new PageReference('/' + ApexPages.currentPage().getParameters().get('oppid'));
        		stdController.save();
        		save.setRedirect(true);
        		return save;
        	}
        }
        catch(DMLException ex){
        	ApexPages.addMessages(ex);
        	return null;
        }
    }   
}
Test Class:
@isTest 
public with sharing class CreateControllerTest {
    static testMethod void testCreateController(){
    	
    	Account testAcct = new Account(Name='Test Create Controller');
    	insert testAcct;
    	
    	Opportunity opp = new Opportunity(Name = 'Test Opportunity1',Account = testAcct,Project_Start_Date__c = Date.newInstance(2017, 12, 15),Delivery_End_Date__c = Date.newInstance(2018, 9, 15),Forecast_Amount__c = 50000, StageName = 'Continued Development of Project',Opportunity_Region__c = 'UK',CloseDate = Date.newInstance(2011, 12, 15), Is_Test__c =TRUE, Automatic_Forecasting__c = FALSE, Test_Date__c = Date.newInstance(2017, 12, 18));
    	insert opp;
    	
    	Opportunity_Forecast__c oppf = new Opportunity_Forecast__c(Opportunity__c = opp.id, Value__c = 2000, Forecast_Category__c = 'Upside', Forecast_Period__c = 'Next Quarter');
    	insert oppf;
    	
    	Test.StartTest();
    	
    	PageReference pageRef = Page.NewForecast;
		Test.setCurrentPage(pageRef);
		pageRef.getParameters().put('id',oppf.Id);
    	ApexPages.StandardController sc = new ApexPages.StandardController(oppf);
        CreateController testOppForecast = new CreateController(sc);
 
        testOppForecast.saveAndReturn();
        Test.StopTest();
    }
}
Any ideas what I'm doing wrong? I've done some reading on the error I'm getting but most cases are where the record hasn't been created. 
Here is vf page
<apex:page controller="EmailSending">
    <apex:form id="ww">    	
        <apex:pageBlock >
            <apex:pageBlockSection collapsible="false" columns="3" >
            	<apex:pageBlockTable value="{!cts}" var="c">
                	<apex:column headerValue="Name">
                        <apex:commandLink value="{!c.name}" action="{!gettoActivate}" reRender="ww">
                        <apex:param value="{!c.id}" name="varId"/>
                        </apex:commandLink>
                    </apex:column>
                    <apex:column value="{!c.id}" />
                    <apex:column value="{!c.Email}" />
                </apex:pageBlockTable>
           </apex:pageBlockSection>
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Send E-mail" action="{!sendEmail}" />
                <apex:commandButton value="Send VF Template" action="{!sendVFTemp}"/>
                <apex:commandButton value="Send HTML" action="{!sendHTMLTemp}" /> 
                <apex:commandButton action="{!clearit}" value="Reset" reRender="aa" />
            </apex:pageBlockButtons>            
            <apex:pageBlockSection columns="3" id="aa" >            
                <apex:inputText value="{!emailAddress}" label="Enter E-mail Address * :" required="true" />                   
                <apex:inputText value="{!subject}" label="Subject :"/>                  
                <apex:inputTextarea value="{!body}" label="Body :"/>         
            </apex:pageBlockSection>
        </apex:pageBlock>
           
    </apex:form>
</apex:page>
And controller 
public class EmailSending {
    public string emailAddress {get;set;}
    public string subject {get;set;}
    public string body {get;set;}
    
    public list<string> forConversition {get;set;}
    public list<contact> cts	{get;set;}
    public String rec {get;set;}
    
    public Task35(){
        forConversition = new List<string>();
      //  cts	=	new list<contact>();
        cts	=	[SELECT Name,ID,Email FROM Contact limit 10];
       // gg= new Group__c ();
       
    }
    
    public void sendEmail(){
      // subject	=	'the address is'+a;
       //body		=	'this is a test body that is being sent to '+a;
        //system.debug(a);
         Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();       	
       		forConversition.add(emailAddress);               
        		email.setToAddresses(forConversition);
           // System.debug('email'+emailAddress);
        	email.setSubject(subject);
        	email.setPlainTextBody( body );
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});  
       
    }
    public void gettoActivate(){
        system.debug('how are you guys');
        rec	=	ApexPages.CurrentPage().getParameters().get( 'varId' );
         system.debug('recid is'+rec);
       // return new pagereference(rec);
    }
    public void sendHTMLTemp(){
        //system.debug(varID);
        rec	=	ApexPages.CurrentPage().getParameters().get( 'varId' );
        system.debug(rec);
      //  cts	=	[SELECT ID from Contact where ID=:rec];
        EmailTemplate et = [SELECT Id FROM EmailTemplate where name =:'HTML temp1'];
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();       	
       		forConversition.add(emailAddress);               
        		email.setToAddresses(forConversition);
        		email.setTemplateId(et.Id);
        	email.setTargetObjectId(rec);
           // System.debug('email'+emailAddress);
        	//email.setSubject(subject);
        	//email.setPlainTextBody( body );
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
    public void sendVFTemp(){
         rec	=	ApexPages.CurrentPage().getParameters().get( 'varId' );
        system.debug(rec);
        EmailTemplate et = [SELECT Id FROM EmailTemplate where name =:'VF page e-mail Template'];
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();       	
       		forConversition.add(emailAddress);               
        		email.setToAddresses(forConversition);
        		email.setTemplateId(et.Id);
        	email.setTargetObjectId(rec);
           // System.debug('email'+emailAddress);
        	//email.setSubject(subject);
        	//email.setPlainTextBody( body );
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
    
    public void clearit(){
        emailAddress = Null;
        subject= Null;
        body= Null;
    }
}


 
public class Task0 {   
    public List<wrapGroup> acc{get;set;}
    public List<Group__c> abc{get;set;}
    public List<Group__c> abc1{get;set;}
    public string Recid{get;set;}
    
    public Task0(){    
        {
            acc=new List<wrapGroup>();
            abc1 = new List<Group__c>();
              List<Group__c> gcc=[SELECT name,id,Course_Name__c,Degree__c,Mobile__c FROM Group__c];
              For(Group__c g : gcc  ){
              acc.add(new wrapGroup(g));
              }
          }
          system.debug(acc);
  }   
    public pageReference del(){
      // abc=new List<Group__c>();
         for(wrapGroup a : acc){
        if(a.checkbox1 == true){            
           abc1.add(a.gname);           
           //string recid = ApexPages.CurrentPage().getParameters().get('a.id');            
            //string recid;
            system.debug(' abc1'+abc1);
            //abc=[select id FROM Group__c WHERE id= :Recid];
            //system.debug('List'+abc);                      
            }
        }
          delete abc1;          
        return null;
    }   
    public class wrapGroup{
        public Group__c gname{get;set;}
            public boolean checkbox1{get;set;}       
    public wrapGroup(Group__c g){
        gname=g;
        checkbox1=false;
    }     
    }
 }


 
<apex:page controller="Task0" >
    <apex:form >
       <script>
         function enableDisable(cb)
    {
      $("input:checkbox[id*=looped]").removeAttr('checked');
      $(cb).attr('checked', 'checked');
    }
		</script>
        <apex:pageBlock >
            <!--<apex:commandButton value="Delete" action="{!Del}" />-->
            <apex:pageBlockTable value="{!acc}" var="a" >
                <apex:column value="{!a.gname.name}"/>
                <apex:column value="{!a.gname.Mobile__c}"/>
                <apex:column value="{!a.gname.Course_Name__c}"/>
               <!-- <apex:column >
                    <apex:outputField value="{!a.gname.Id}">
                <apex:param value="{!a.gname.id}" assignTo="{!Recid}" />  
                    </apex:outputField>
                </apex:column>-->
                <apex:column title="Select to Delete" >
                   
                 <apex:inputCheckbox id="looped" value="{!a.checkbox1}" onclick="enableDisable(this)" />                   
                        
                </apex:column>
               
            </apex:pageBlockTable>
         </apex:pageBlock>
     </apex:form>   
</apex:page>

 
Need recommendations from the community. What is the best resource that you would recommend for a newbie to learn Visualforce? That includes YouTube,books, websites, blogs, podcasts, etc.
Hi, All 


*what are all the Procedure to implement the integration using web services URL?
*How to consume the web services in apex class Or call the web services in apex class?

Advance Thanks  To all
Hi All,
I am facing one error while executing the following code.
Please give your suggestion to combat this error and improve my code.
Note : Error is mentioned in Title.
public class Apex_DML 
{
     public void upsertData() // Insert and Update in One Call
        {
                Demo__c[] dl=[select name from Demo__c where Number__c=3]; //Existing Record Fetched
        
                for(Demo__c t:dl)
                {
                        t.Name='Lion'; // Existing Record Updated
                 }        
     
               Demo__c nd=new Demo__c(Name='TrailHead',Number__c=10); // New record Created        
                 dl.add(nd);
        
                try
                {
                         upsert dl Number__c;
                }
                catch(DmlException e)
                {
                        System.debug(e.getMessage());
                }
       
                System.debug('Record Upserted..');        
        
        }
}

 
Hello, I m very new to Apex programming and was looking for the best way to write an APEX class that will give me Opportunity Header Data and its related Products (line item on that Opportunity) where the created and modified date is the date I pass to this class. I know how to write this SQL but wanted to know how to get this in Apex Class. 

Thanks 
DJ
  • December 25, 2017
  • Like
  • 0
How can I create the exact image below on my visualforce page rendered as PDF? "ABC INDUSTRIES, INC." will autopopulate from the Account Name of the record from the custom object, however I would like the account name to appear bold and in ALL CAPS as seen in the image.

User-added image
Hello,
I have the below async class  and its test.
What I failing with is how to cover test percentage for Messaging.SingleEmailMessage Invocation when callout fails..
I have already gone through multiple links on stack exchange and Apex forum, tried some approaches but none worked for me.
Can some one please assist in what I may be doing wrong here.
Code coverage under SUCCESS is 78% while under FAILURE is 24%.
 
public class DeleteExpertInSelene {
	//method to be invoked by ProcessBuilder apex
    @InvocableMethod
    public static void deleteAccountInSelene(List<Id> acctIds){
        Account acc = [SELECT Selene_ID__c FROM Account WHERE Id = :acctIds[0]];   
        System.enqueueJob(new QueueableSeleneCall(acc.Selene_ID__c, acc.Id));
    }
    
    // future method to make delete experts
    @Future(callout=true)
    private static void deleteToSelene(Decimal userId, Id acctId) {				 
        List<String> EMAIL_RESULTS = new List<String>{System.Label.Email_Selene_List};
        List<String> EMAIL_RESULTS_2 = new List<String>{System.Label.Email_Selene_List_2};
        String tokenVar = '';
        tokenVar = 'Token '+GetSeleneID.getAuthorizationToken();
        HTTPRequest req = new HTTPRequest();
        req.setEndPoint('some api'+ userId);     
        req.setMethod('DELETE');
        req.setHeader('authorization',tokenVar);
        req.setHeader('Accept','application/json;charset=UTF-8');
        req.setHeader('Content-Type', 'application/json;charset=UTF-8'); 
        req.setHeader('Cache-Control', 'no-cache'); 
        req.setHeader('x-api-key', 'some key');
        req.setTimeout(120000);                                         
        HTTP http = new HTTP();
        HTTPResponse res = http.send(req);
        
        if(res.getStatusCode() != 200){
            System.debug('Failure: ' + res.getStatusCode() + ' ' + res.getStatus());
            // Send email
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setToAddresses(EMAIL_RESULTS);
            mail.setCcAddresses(EMAIL_RESULTS_2);
            mail.setSenderDisplayName('Salesforce Administrator');
            mail.setSubject('Delete To Selene Failed ');
            mail.setPlainTextBody('some mssg');
            Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{mail});
        } else {
            if(res.getStatusCode() == 200){
                System.debug('Success: ' + res.getBody() + ' ' + res.getStatus());
        }
        
    }
           
 }   
    //queueable class to enque the put request
    class QueueableSeleneCall implements System.Queueable, Database.AllowsCallouts {
        private Decimal seleneId;
        private String Id;
        public QueueableSeleneCall(Decimal userId, Id acctId){             
            this.seleneId = userId;
            this.Id = acctId;
        }
        public void execute(QueueableContext context) {
            deleteToSelene(seleneId, Id);                               
        }
    }
}

Test Class...
@isTest
public class DeleteExpertInSelene_Test {
	  @testSetup static void testSetupdata(){
        //create the account record
        Account acc1 = new Account();
        acc1.Name = 'ABC Corp1';
        acc1.Email__c = 'test@testmail.com';
        acc1.Phone = '5554446767';
        acc1.Legacy_GID__c = '54321';
        acc1.Display_Name__c = 'abc1';
        acc1.Status__c = 'Live';
        acc1.Selene_ID__c = 112233445.00;
        insert acc1;
        //create the account record
        Account acc2 = new Account();
        acc2.Name = 'ABC Corp2';
        acc2.Email__c = 'testmail@test.com';
        acc2.Phone = '6665554343';
        acc2.Legacy_GID__c = '12345';
        acc2.Display_Name__c = 'abc2';
        acc2.Status__c = 'Live';
        acc2.Selene_ID__c = 112233446.00;
        insert acc2;
    
  }
  
       
  @isTest static void testPostCalloutSuccess() {
      Account acc = [Select Id, Name FROM Account WHERE Name = 'ABC Corp1' Limit 1];
      List<Id> accList = new List<Id>();
      accList.add(acc.Id);
      System.assertEquals('ABC Corp1', acc.Name);
      System.assertEquals(1,accList.size());
      // Set mock callout class 
      Test.setMock(HttpCalloutMock.class, new SeleneCalloutMockService()); 
      // This causes a fake response to be sent
      // from the class that implements HttpCalloutMock. 
      
      Test.startTest();
      DeleteExpertInSelene.deleteAccountInSelene(accList);
      //Integer invocations = Limits.getEmailInvocations();
      Test.stopTest(); 
      
      
      // Verify that the response received contains fake values        
      acc = [select Selene_ID__c from Account where id =: acc.Id];
      System.assertEquals(112233445.00,acc.Selene_ID__c);
      
    }
    
    @isTest static void testPostCalloutFailure() {
        Account acc = [Select Id, Name FROM Account WHERE Name = 'ABC Corp2' Limit 1];
        List<Id> accList = new List<Id>();
        accList.add(acc.Id);
        System.assertEquals('ABC Corp2', acc.Name);
        System.assertEquals(1,accList.size());  
        
        // Set mock callout class
        Test.setMock(HttpCalloutMock.class, new SeleneCalloutMockService()); 
        // This causes a fake response to be sent
        // from the class that implements HttpCalloutMock. 
        Test.startTest();
        DeleteExpertInSelene.deleteAccountInSelene(accList);
        Integer invocations = Limits.getEmailInvocations();
        Test.stopTest();        
        // Verify that the response received contains fake values        
        acc = [select Selene_ID__c from Account where id =: acc.Id];
        System.assertEquals(112233446.00,acc.Selene_ID__c);
        System.assertEquals(1, invocations, 'An email should be sent');
    }  
    
}
Any help is appreciated.
Thanks!


I have a one custom field in Account object Called 'Rate__c' and My package Namespace is 'XYZ'. After installing package to any org; XYZ__Rate__c  field gets created . My requirement is to create field without namespace (only Rate__c).
Hi Developers,

I am write a trigger on Contact Object. trigger work on single record but on bulk data its not working properly.
My code is Here
trigger UpdateContactName on Contact (before insert){
    set<id> setAccountId=new set<id>();
    if (Trigger.isAfter) {
        if (Trigger.isInsert)  {
            for(contact con : Trigger.new){
                if(con.accountId != null){
                   setAccountId.add(con.AccountId);   
                }
                list<string> conId = new list<string>();
                for(contact c : [select id, FirstName, lastName from contact where AccountId IN : setAccountId]){
                    conId.add(c.Id);
                }
                for(contact cont : trigger.new){
                    cont.FirstName = '';
                    cont.lastName = '';
                    cont.FirstName = 'Pr';
                    cont.lastName = string.valueof(conId.size());
                }
                
            }
        } 
    } 
}
Any one can correct my code or any suggetions 
Thanks in advance
 
/*********************************************************************

* Description - Apex REST service with GET and POST methods

* Author - AP

<u>Json format</u>

{

"name" : "Akash",

"phone" : "8826031286",

"website" : "www.akashmishra.co.in"

}

***********************************************************************/

@RestResource(urlMapping='/v3/accounts/*')

global with sharing class REST_AccountService_V4 {

@HttpPost

global static AccountWrapper doPost(String name, String phone, String website) {

RestRequest req = RestContext.request;

RestResponse res = RestContext.response;

AccountWrapper response = new AccountWrapper();

Account acct = new Account();

acct.Name = name;

acct.Phone = phone;

acct.Website = website;

insert acct;

response.acctList.add(acct);

response.status = 'Success';

response.message = 'Your Account was created successfully.';

return response;

}

@HttpGet

global static AccountWrapper doGet() {

RestRequest req = RestContext.request;

RestResponse res = RestContext.response;

AccountWrapper response = new AccountWrapper();

String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

if(doSearch(accountId))

{

searchAccounts(req, res, response);

}

else

{

findAccount(res, response, accountId);

}

return response;

}

// If the item to the right of the last forward slash is "accounts", the request went to

//v3/accounts?Name=Akash

// Else the request went to v3/accounts/&lt;something&gt;, which is not a search, but a specific

//entity

private static boolean doSearch(String accountId) {

if(accountId == 'accounts') {

return true;

}

return false;

}

//If the request came to /v3/accounts, then we want to execute a search

Public static void searchAccounts(RestRequest req, RestResponse res,

AccountWrapper response) {

//Use the RestRequest's params to fetch the Name parameter

String searchTerm = req.params.get('Name');

if(searchTerm == null || searchTerm == '') {

response.status = 'Error';

response.message = 'You must provide a Name for your search term.';

res.StatusCode = 400;

}

else {

String searchText = '%'+searchTerm+'%';

List&lt;Account&gt; searchResults =

[SELECT Id, Name, Phone, Website FROM Account WHERE Name LIKE : searchText];

if(searchResults != null &amp;&amp; searchResults.size() &gt; 0) {

response.acctList = searchResults;

response.status = 'Success';

response.message = searchResults.size()

+ ' Accounts were found that matched your search term.';

}

else {

response.status = 'Error';

response.message =

'No Accounts were found based on that Name, please search again.';

}

}

}

&nbsp;

//If the request came to v3/accounts/sometext then we want

//to find a specific account

Public static void findAccount(RestResponse res, AccountWrapper response,

String accountId) {

// Provided we recevied an External Id, perform the search and return the results

if(accountId != null &amp;&amp; accountId != '') {

List&lt;Account&gt; result = [SELECT Id, Name, Phone, Website FROM Account

WHERE External_Id__c =: accountId];

if(result != null &amp;&amp; result.size() &gt; 0) {

response.acctList.add(result[0]);

response.status = 'Success';

}

else {

response.status = 'Error';

response.message = 'This account could not be found, please try again.';

res.StatusCode = 404;

}

}

// If the request came to /v3/accounts/ (without an Account Id),

//return an error

else {

response.status = 'Error';

response.message = 'You must specify an External Id.';

res.StatusCode = 400;

}

}

global class AccountWrapper {

public List&lt;Account&gt; acctList;

public String status;

public String message;

public AccountWrapper(){

acctList = new List&lt;Account&gt;();

}

}

}



can anybody resolve this issue
 
I need to use Today's date in a format like 2016-03-22T03:44:34.000-07:00 in a where clause in a query. Can you please help how to format this.
like 

SELECT id,name,SubscriptionId,createdDate FROM Amendment where createdDate = today

and today needs to be in this format, e.g.
2016-03-22T03:44:34.000-07:00

So, if I get system.today(); I need your help how to format that as I mentioned above.

Thank you
I have a Code in which i am using apex:inputField for lookup field. when i am getting this field value in script it gives me the name of the record selected.
I want to get the ID of the record selected either in javascript variable or in apex controller.
Page------------------------------->>

<apex:page Controller="ApexParamController">
    <script>
    function fire(){
        var fr=document.getElementById('{!$Component.frm.acc}').value;
        alert('test:: '+fr);
    }
    </script>
    <apex:form id="frm">
        <apex:inputfield value="{!contact.AccountId}" id="acc"/>
        <apex:commandButton onclick="fire();" value="Save" action="{!print}" />
    </apex:form>
</apex:page>
 
Class------------------->>

public class ApexParamController {
    Public Contact contact{get;set;}
    public void print(){
        contact = new Contact();
        system.debug('Account::'+contact.AccountID);
    }
}

 
Hi folks, 

This seems like a weird one (must be dead simple, but not seeing it).

I'm simply trying to access an Http response header key value as specified in the docs, When I try to save, the compiler is complaining about the method signature. I've tried in a few different orgs to make sure somehow the HttpResponse class hadn't been overridden somehow...

Thanks for any clues/suggestions.
public class HttpTesting {
    public HttpTesting() {
        String aString = 'aHeaderKey';
        HttpRequest anHttpRequest = new HttpRequest();
		HttpResponse anHttpResponse = new Http().send(anHttpRequest);

        System.debug('---> anHttpResponse.getHeaderKeys(): ' + anHttpResponse.getHeaderKeys());
        System.debug('---> anHttpResponse.getHeaderKey(aString): ' + anHttpResponse.getHeaderKey(aString));  // <--- 'Method does not exist or incorrect signature: void getHeaderKey(String) from the type System.HttpResponse'
    }
}

 
  • January 14, 2018
  • Like
  • 0
I have a controller extension for a custom create child object page to take me back to the correct page after editing and to allow me to have an erorr message wthout using a validation. The controller works exactly as it should but I am having issues writing the test class for it. Iget the error "system.queryexception: list has no rows for assignment to sobject" My code is as below:
Controller:
public with sharing class createController {
	public String oppId {get;set;}
	public Opportunity opp;
	public Opportunity_Forecast__c oppf {get;set;}
	private ApexPages.StandardController stdController; 
	
    public createController(ApexPages.StandardController stdController) {
    	this.stdController = stdController;
        oppf = (Opportunity_Forecast__c)stdController.getRecord();
        String oppid = (oppf.Opportunity__c);
        String ID = ApexPages.currentPage().getParameters().get('oppid');
        opp = [select Automatic_Forecasting__c from Opportunity where Id =:ID]; 
        if (ID != null){
        	oppf.Opportunity__c= ID;   
        }   
    }
	
	public PageReference cancelAndReturn() 
    {
    	PageReference cancel = new PageReference('/' + ApexPages.currentPage().getParameters().get('oppid'));
        cancel.setRedirect(true);
 		return cancel;	
    }
	
	public PageReference saveAndReturn()
    {
        try{
        	if(opp.Automatic_Forecasting__c == true){
        		ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: Upside Automation must be disabled on the opportunity page before editing forecasts.');
        		ApexPages.addMessage(myMsg);
        		return null;
        	}
        	else{
        		upsert oppf;
        		PageReference save = new PageReference('/' + ApexPages.currentPage().getParameters().get('oppid'));
        		stdController.save();
        		save.setRedirect(true);
        		return save;
        	}
        }
        catch(DMLException ex){
        	ApexPages.addMessages(ex);
        	return null;
        }
    }   
}
Test Class:
@isTest 
public with sharing class CreateControllerTest {
    static testMethod void testCreateController(){
    	
    	Account testAcct = new Account(Name='Test Create Controller');
    	insert testAcct;
    	
    	Opportunity opp = new Opportunity(Name = 'Test Opportunity1',Account = testAcct,Project_Start_Date__c = Date.newInstance(2017, 12, 15),Delivery_End_Date__c = Date.newInstance(2018, 9, 15),Forecast_Amount__c = 50000, StageName = 'Continued Development of Project',Opportunity_Region__c = 'UK',CloseDate = Date.newInstance(2011, 12, 15), Is_Test__c =TRUE, Automatic_Forecasting__c = FALSE, Test_Date__c = Date.newInstance(2017, 12, 18));
    	insert opp;
    	
    	Opportunity_Forecast__c oppf = new Opportunity_Forecast__c(Opportunity__c = opp.id, Value__c = 2000, Forecast_Category__c = 'Upside', Forecast_Period__c = 'Next Quarter');
    	insert oppf;
    	
    	Test.StartTest();
    	
    	PageReference pageRef = Page.NewForecast;
		Test.setCurrentPage(pageRef);
		pageRef.getParameters().put('id',oppf.Id);
    	ApexPages.StandardController sc = new ApexPages.StandardController(oppf);
        CreateController testOppForecast = new CreateController(sc);
 
        testOppForecast.saveAndReturn();
        Test.StopTest();
    }
}
Any ideas what I'm doing wrong? I've done some reading on the error I'm getting but most cases are where the record hasn't been created. 
I know that maximum 100 callouts can be done in a single transaction. I just want to know how many can be done in parallel?
I have a scenario where I am scheduling a job throw apex class. 
Datetime sysTime = System.now().addMinutes(5);    
String SchTimer = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' + sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();
system.schedule('scheduleDataJob_'+ SchTimer , SchTimer, new DataScheduleJob(sr));

I want to check whether this job is already scheduled or not? if it is not schedule then it should schedule and if it is scheduled then don't schedule it. 
Here is vf page
<apex:page controller="EmailSending">
    <apex:form id="ww">    	
        <apex:pageBlock >
            <apex:pageBlockSection collapsible="false" columns="3" >
            	<apex:pageBlockTable value="{!cts}" var="c">
                	<apex:column headerValue="Name">
                        <apex:commandLink value="{!c.name}" action="{!gettoActivate}" reRender="ww">
                        <apex:param value="{!c.id}" name="varId"/>
                        </apex:commandLink>
                    </apex:column>
                    <apex:column value="{!c.id}" />
                    <apex:column value="{!c.Email}" />
                </apex:pageBlockTable>
           </apex:pageBlockSection>
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Send E-mail" action="{!sendEmail}" />
                <apex:commandButton value="Send VF Template" action="{!sendVFTemp}"/>
                <apex:commandButton value="Send HTML" action="{!sendHTMLTemp}" /> 
                <apex:commandButton action="{!clearit}" value="Reset" reRender="aa" />
            </apex:pageBlockButtons>            
            <apex:pageBlockSection columns="3" id="aa" >            
                <apex:inputText value="{!emailAddress}" label="Enter E-mail Address * :" required="true" />                   
                <apex:inputText value="{!subject}" label="Subject :"/>                  
                <apex:inputTextarea value="{!body}" label="Body :"/>         
            </apex:pageBlockSection>
        </apex:pageBlock>
           
    </apex:form>
</apex:page>
And controller 
public class EmailSending {
    public string emailAddress {get;set;}
    public string subject {get;set;}
    public string body {get;set;}
    
    public list<string> forConversition {get;set;}
    public list<contact> cts	{get;set;}
    public String rec {get;set;}
    
    public Task35(){
        forConversition = new List<string>();
      //  cts	=	new list<contact>();
        cts	=	[SELECT Name,ID,Email FROM Contact limit 10];
       // gg= new Group__c ();
       
    }
    
    public void sendEmail(){
      // subject	=	'the address is'+a;
       //body		=	'this is a test body that is being sent to '+a;
        //system.debug(a);
         Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();       	
       		forConversition.add(emailAddress);               
        		email.setToAddresses(forConversition);
           // System.debug('email'+emailAddress);
        	email.setSubject(subject);
        	email.setPlainTextBody( body );
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});  
       
    }
    public void gettoActivate(){
        system.debug('how are you guys');
        rec	=	ApexPages.CurrentPage().getParameters().get( 'varId' );
         system.debug('recid is'+rec);
       // return new pagereference(rec);
    }
    public void sendHTMLTemp(){
        //system.debug(varID);
        rec	=	ApexPages.CurrentPage().getParameters().get( 'varId' );
        system.debug(rec);
      //  cts	=	[SELECT ID from Contact where ID=:rec];
        EmailTemplate et = [SELECT Id FROM EmailTemplate where name =:'HTML temp1'];
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();       	
       		forConversition.add(emailAddress);               
        		email.setToAddresses(forConversition);
        		email.setTemplateId(et.Id);
        	email.setTargetObjectId(rec);
           // System.debug('email'+emailAddress);
        	//email.setSubject(subject);
        	//email.setPlainTextBody( body );
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
    public void sendVFTemp(){
         rec	=	ApexPages.CurrentPage().getParameters().get( 'varId' );
        system.debug(rec);
        EmailTemplate et = [SELECT Id FROM EmailTemplate where name =:'VF page e-mail Template'];
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();       	
       		forConversition.add(emailAddress);               
        		email.setToAddresses(forConversition);
        		email.setTemplateId(et.Id);
        	email.setTargetObjectId(rec);
           // System.debug('email'+emailAddress);
        	//email.setSubject(subject);
        	//email.setPlainTextBody( body );
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
    
    public void clearit(){
        emailAddress = Null;
        subject= Null;
        body= Null;
    }
}


 
I have a custom object with 5 different record types. There are some similar fields between record types, but for the most part the content can vary greatly. Can I create one query that accomodates all 5 record types? Is it better to create a query for each record type?
Trigger:
trigger Account_AU on Account (before insert, before update, after insert, after update)
{
    system.debug('START --------------'+AccountTriggers.toBeExecuted);
    if(AccountTriggers.toBeExecuted){
    if(Trigger.isBefore) {
        if(Trigger.isInsert) {
        AccountTriggers.setRecordType(Trigger.new, (new Map<Id, Account>()));
           AccountTriggers.updateAccFields(Trigger.new,(new Map<Id, Account>()),true);
          AccountTriggers.updateCustomerCategories(Trigger.new, null);
        } else if(Trigger.isUpdate) {
            //AccountTriggers.retainFieldsWhenAccountIsInactive(Trigger.newMap, Trigger.oldMap);
            AccountTriggers.setRecordType(Trigger.new, Trigger.oldMap);
            AccountTriggers.updateAccFields(Trigger.new, Trigger.oldMap,false);
        }
        
    } else if(Trigger.isAfter) {
        if(Trigger.isInsert) {
    
            AccountTriggers.FlagContactsForAccountSharing(Trigger.New, null);
            if(!utility.IsAccountAfterInsertCalled){
                utility.IsAccountAfterInsertCalled=true;
                utility.IsAccountAfterUpdateCalled=true;
                
              AccountLocationMappingtoStore.deepCloneAccountLocation(Trigger.new,trigger.oldMap,true);
          
                AccountTriggers.deepCloneAccount(Trigger.new, (new Map<Id, Account>()));
                AccountTriggers.CheckdeptAccount(Trigger.new);
                    
            }
            
        } else if(Trigger.isUpdate) {
             system.debug('inside update');
            AccountTriggers.FlagContactsForAccountSharing(Trigger.New, Trigger.oldMap);
            AccountTriggers.CheckdeptAccount(Trigger.new);
            AccountTriggers.managingCountry_Update(Trigger.New, Trigger.oldMap);
            if(!utility.IsAccountAfterupdateCalled){
                utility.IsAccountAfterupdateCalled=true;
                //To update the existing location.
                AccountTriggers.deepCloneAccount(Trigger.new,Trigger.oldMap);
              system.debug('entering inside');
               AccountTriggers.updateCustomerCategories(Trigger.new, Trigger.oldMap);
                /** To create/update store and location--B-160815**/
              AccountLocationMappingtoStore.deepCloneAccountLocation(Trigger.new,trigger.oldMap,false);
                
            }
        }
    } // end isAfter
        
    }
}

class and Method:
public static void updateCustomerCategories(List<Account> accountList, Map<Id, Account> oldAccts) {
       map<string,Account> parentMap = new  map<string,Account>();
        map<string,list<Account>> childMap = new  map<string,list<Account>>();
        List<Account> updateAccount = new List<Account>();
        Account accRef=new Account();
        // if(!shouldRun('UpdateCustomerCategories')) return;
        
        
        Set<Id> accIds = new Set<Id>();
        Map<String,List<Account>> accInserIdMap = new  Map<String,List<Account>>();
        for(Account acc:accountList){
            
            Account oldAcct = null;
            if(oldAccts != null && oldAccts.get(acc.Id) != null) {
                oldAcct = oldAccts.get(acc.Id);
            }
            if(oldAcct != null){
                if(( oldAcct.Customer_Categories_for_MC__c != acc.Customer_Categories_for_MC__c )) {
                    parentMap.put(acc.id,acc);
                    accIds.add(acc.Id);
                    //if it is only one parent then updated account will be assigned to this account reference
                    accRef =  acc;
                }
            }
            //It is for Inserted records
            if(oldAcct == null  && acc.parentid != null && acc.IsSoldTo__c==true ){
                  system.debug('insiode insert'+acc.parentid);
                if(accInserIdMap.containskey(acc.parentid)){ //need to check when it will work
                    accInserIdMap.get(acc.parentid).add(acc);
                }
                else{
                    accInserIdMap.put(acc.parentid,new List<Account>{acc});
                }
            }
            
           else if(oldAcct != null  && acc.parentid != null && acc.IsSoldTo__c==true ){
               system.debug('insiode update'+acc.parentid);
                if(accInserIdMap.containskey(acc.parentid)){ //need to check when it will work
                    accInserIdMap.get(acc.parentid).add(acc);
                }
                else{
                    system.debug('insiode update1'+acc.parentid);
                    accInserIdMap.put(acc.parentid,new List<Account>{acc});
                }
            }
        }
       
        //This loop only for inserted records.
        if(accInserIdMap.size() > 0){
              system.debug(accInserIdMap+'accInserIdMap############');
            List<Account> accList = [select Customer_Categories_for_MC__c,Customer_Category__c,Primary_Category_for_MC__c from Account where id in:accInserIdMap.keyset()];
                   system.debug(accList+'accList############');
            Set<string> newCatSet = new Set<string>();
            if(accList.size() > 0){
                for(Account acc:accList){                                          
                    for(Account accRefNew:accInserIdMap.get(acc.id)){
                        if(accRefNew.Customer_Categories_for_MC__c != null){
                            /******************changes on 5th******************/
                            
                            if(accList.size() > 0){
                                if(accList[0].Customer_Category__c!=null && accList[0].Customer_Category__c.split(';').size()>0){
                                    Pattern nonAlphanumeric = Pattern.compile('[^a-zA-Z;\'/ ]');
                                    Matcher matcher = nonAlphanumeric.matcher(string.escapeSingleQuotes(accList[0].Customer_Category__c));
                                    string st =matcher.replaceAll('').trim().replace('; ', ';');
                                    for(String stCat: st.split(';')){
                                         newCatSet.add(stCat);
                                    }
                                }
                            }
                            
                            
                                if(accRefNew.Customer_Category__c!=null && accRefNew.Customer_Category__c.split(';').size()>0){
                                    Pattern nonAlphanumeric = Pattern.compile('[^a-zA-Z;\'/ ]');
                                    Matcher matcher = nonAlphanumeric.matcher(string.escapeSingleQuotes(accRefNew.Customer_Category__c));
                                    string st =matcher.replaceAll('').trim().replace('; ', ';');
                                    for(String stCat: st.split(';')){
                                         newCatSet.add(stCat);
                                    }
                                }

                            Set<String> catSet = new Set<String>();
                            if(acc.Customer_Categories_for_MC__c!=null){
                                for(String stCat: acc.Customer_Categories_for_MC__c.split(';')){
                                     catSet.add(stCat);
                                 }
                            }
                                
                            for(String stCat: accRefNew.Customer_Categories_for_MC__c.split(';')){
                                     catSet.add(stCat);
                                 }
                            
                            String custCategory = '';
                            String custCategoryMC = '';
                           Integer i=0;
                            for(String catValue : newCatSet){
                                i++;
                                custCategory += i+' '+catValue+';';
                                
                            }
                            for(String catValue : catSet){
                               
                                custCategoryMC += catValue+';';
                            }
                           
                            custCategory= custCategory.substring(0,custCategory.length()-1);
                            custCategoryMC= custCategoryMC.substring(0,custCategoryMC.length()-1);
                            
                            
                            //custCategory.charAt(custCategory.length()-1) = '';
                            
                            /**************changes made now***********************/
                           
                            acc.Customer_Categories_for_MC__c = custCategoryMC;
                            acc.Primary_Category_for_MC__c = accRefNew.Primary_Category_for_MC__c;
                            acc.Customer_Category__c  = custCategory;
                          
                            //acc.Customer_Category__c  = accRefNew.Customer_Category__c;
                            
                            }
                        }
                    
                }
                update accList;
                 system.debug('accList'+accList);
            }
        }
       
        // The below loop will run for the update of the Account
        if(!accIds.isEmpty()){
            system.debug('inside account id'+accIds.size());
            if(accIds.size()==1){
              
                getAllChildAccountIds(accIds);
                system.debug('accIds'+accIds);
                for(Account acc:accUpdatenewList){
                  
                    if(accRef.Customer_Categories_for_MC__c != null){
                     
                        acc.Customer_Categories_for_MC__c = accRef.Customer_Categories_for_MC__c;
                        //  if(acc.inherit__c == true){
                        acc.Customer_Category__c = accRef.Customer_Category__c;
                        acc.Primary_Category_for_MC__c = accRef.Customer_Categories_for_MC__c.split(';')[0];
                        //  }
                        acc.IgnoreValidation__c = true;
                    }
                }
           
                if(accUpdatenewList.size() > 0){
                    utility.IsAccountAfterupdateCalled=true;
                    update accUpdatenewList;
                }
            }
            
            else{
                Database.executeBatch(new Batch_CustomerCategoryUpdate(accIds), (Test.isRunningTest() ? accIds.size() : 1) );
            }
            
            
        }
        
        /* catch(Exception ex){
System.debug('Cat Exception'+ex.getmessage());
} */
    }
    
    
    // Return list of all child Account Ids
    public static void getAllChildAccountIds(set<Id> setAccId){
        Set<Id> tempIdSet=new Set<Id>();
        for(Account acc:[Select Id, name,Customer_Category__c, Synchronize__c,Customer_Categories_for_MC__c,inherit__c,Primary_Category_for_MC__c from Account where parentid in :setAccId]){
            
            accUpdatenewList.add(acc);
            tempIdSet.add(acc.id);
            
        }
        if(tempIdSet.size()>0){
            setAccountIds.addAll(tempIdSet);
            getAllChildAccountIds(tempIdSet);
        }
    }
    public static void updateAccFields(List<Account> accountList, Map<Id, Account> oldAccts,boolean check){
             Id locationRecordID = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Location').getRecordTypeId();
        List<account> accUpdateList = new List<account>();
        
        //Following else loop will only run for the update of Account
        if(oldAccts != null&&check==false){
            Map<string,Account> soldToAccMap = new Map<string,Account>();
            Map<string,Account> soldToAccMap1 = new Map<string,Account>();
            Map<string,Account> sapAccNumberMap = new Map<string,Account>();
            
            for(Account acc:accountList){
               
                if(acc.SAPAccountNum__c==null && acc.IsSoldTo__c==false && locationRecordID==acc.RecordTypeId&&( acc.CustomerDistributionTier__c != oldAccts.get(acc.id).CustomerDistributionTier__c || acc.Managing_Country__c != oldAccts.get(acc.id).Managing_Country__c ||acc.Lead_Category__c!=oldAccts.get(acc.id).Lead_Category__c||
                                                        acc.SalesOrg__c != oldAccts.get(acc.id).SalesOrg__c||acc.Account_Class__c != oldAccts.get(acc.id).Account_Class__c || acc.Channel_Class_Name__c != oldAccts.get(acc.id).Channel_Class_Name__c||acc.customer_Category__c!=oldAccts.get(acc.id).customer_Category__c)){
                                                           
                                                            soldToAccMap.put(acc.id,acc);
                                                            soldToAccMap1.put(acc.Sold_to__c,acc);
                                                           
                                                            if(acc.SAPAccountNum__c != null && acc.SAPAccountNum__c!=''){
                                                                sapAccNumberMap.put(acc.SAPAccountNum__c,acc); 
                                                            }
                                                        }
            }
            if(soldToAccMap.size() > 0 ){
            
                set<string> soldTo=soldToAccMap.keyset();
                set<string> soldTo1=soldToAccMap1.keyset();
                set<string> sapSet= new set<string>();
                
                string query = 'select id,Sold_to__c,Customer_Category__c,Lead_Category__c,Sold_To_Number_Text__c,GBHGeo__c,GBHTerritory__c, CountryCode__c,SalesOrg__c,CustomerDistributionTier__c,SAPAccountNum__c,Channel_Class_Name__c,Managing_Country__c,Account_Class__c from account where ID in:soldTo1';
               
                if(sapAccNumberMap.size() > 0){
                    sapSet=sapAccNumberMap.keyset();
                //query = query+' or Sold_To_Number_Text__c in:sapSet';
                }
            
                for(Account accRef:(List<Account>)Database.query(query)){
                                     
                 
                    if(accRef.Sold_To_Number_Text__c != '' && accRef.Sold_to__c == null){
                        
                        Account acc = new Account(id = accRef.id);
                        acc.CustomerDistributionTier__c = accRef.CustomerDistributionTier__c;
                        acc.Channel_Class_Name__c = accRef.Channel_Class_Name__c;
                        acc.Managing_Country__c   = accRef.Managing_Country__c;
                        acc.SalesOrg__c=accRef.SalesOrg__c;
                        acc.Account_Class__c      =  accRef.Account_Class__c;
                         acc.Lead_Category__c=accRef.Lead_Category__c;
                        acc.Customer_Category__c=accRef.Customer_Category__c;
                        // if(acc.Managing_Country__c == null){
                        
                        // }
                        
                        accUpdateList.add(acc);
                    }
                }
            }
        }
        
        
        if(accUpdateList.size() > 0){
            utility.IsAccountAfterUpdateCalled=true;
            Update accUpdateList;
        }
        
    

}
I have REST API class, i am trying to cover 100% code coverage. Currently i have 71 % code coverage. Code in bold are not covered. Can you please guide me.

Apex class:
@RestResource(urlMapping='/mrtValidateNonFSLUser/*')

// This rest service is used by Web-application in order to
// MRT user who are non-FSL.
// Retrieves username and password as post validates against "MRT__c" Table  
// Sample Data
// {
//   "sUsername": "me@4richie.com",
//   "sPassword": "Epirc1961"
//}
global class mrtValidateNonFSLUser {
    //Input Class
    public class mrtCredintials{
        public String sUsername;
        public String sPassword;
    }    
    
    @HttpPost
    global static Boolean mrtValidateNonFSLUser () {
        //Variables declaration.        
        List<MRT__c> lstCKSWUser;
        mrtCredintials objCred;        
        RestRequest objReq = RestContext.request;
        RestResponse objRes = RestContext.response;   
        objRes.addHeader('Content-Type','applicatin/json');
        
        try{            
            objCred  = (mrtCredintials) JSON.deserialize(objReq.requestBody.toString(), mrtCredintials.class);
        }
        Catch(Exception objExp){
           return false; //Logging and possible alert to tech team along with exception message.???
        }
         if(objCred != NULL){
            lstCKSWUser = [SELECT Email__c From MRT__c WHERE Email__c =: objCred.sUsername AND Password__c =: objCred.sPassword AND Active__c = true];
            return lstCKSWUser.size() > 0 ? true : false;
            }
        return false;
    }       
}


TEST class:
@IsTest
public class Test_mrtValidateNonFSLUser {
     static testMethod void Method1() {
      MRT__c mrt1 = new MRT__c(
      Name = 'MRT One',
      City__c = 'city', 
      State__c = 'cp', 
      Zipcode__c = '123456',
      MRTLocation__Latitude__s = 33.9153,
      MRTLocation__Longitude__s =-118.351309,
               Email__c = 'test@epi.com',
               password__c = 'test1234'
      );
    insert mrt1; 
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
        
        req.requestURI = '/services/apexrest/mrtValidateNonFSLUser';  
        req.httpMethod = 'POST';
        RestContext.request = req;
        RestContext.response = res;
       test.startTest();
         mrtValidateNonFSLUser.mrtValidateNonFSLUser();
          test.stopTest();
     }
      }
    


 
  • January 07, 2018
  • Like
  • 0
error at comment line. 

@RestResource(urlMapping='/RestWebservice1/*')
global class RestWebservice1 {
@HttpGet
    global static string doGet(){
       List<Account> accs = [select Name,Phone from Account limit 4];
        System.JSONGenerator jg = JSON.createGenerator(true);
        jg.writeStartObject();
        jg.writeFieldName('Status');
        if(accs.size()>0){
            jg.writeString('Success');
            jg.writeNumberField('count',accs.size());
            jg.writeFieldName('Accounts');
            for(Account a: accs){
                jg.writeStartObject();    // I'm getting error here 
                jg.writeStringField('Name', a.Name);
                jg.writeStringField('Phone', a.Phone);
                jg.writeEndObject();
            }
        }else{
            jg.writeString('Failed');
            jg.writeStringField('Reason', 'No Records Found');    
        }
        jg.writeEndObject();
            string result=jg.getAsString();
            System.debug('Json String :'+result);
        return result;
    } 
}
public class Task0 {   
    public List<wrapGroup> acc{get;set;}
    public List<Group__c> abc{get;set;}
    public List<Group__c> abc1{get;set;}
    public string Recid{get;set;}
    
    public Task0(){    
        {
            acc=new List<wrapGroup>();
            abc1 = new List<Group__c>();
              List<Group__c> gcc=[SELECT name,id,Course_Name__c,Degree__c,Mobile__c FROM Group__c];
              For(Group__c g : gcc  ){
              acc.add(new wrapGroup(g));
              }
          }
          system.debug(acc);
  }   
    public pageReference del(){
      // abc=new List<Group__c>();
         for(wrapGroup a : acc){
        if(a.checkbox1 == true){            
           abc1.add(a.gname);           
           //string recid = ApexPages.CurrentPage().getParameters().get('a.id');            
            //string recid;
            system.debug(' abc1'+abc1);
            //abc=[select id FROM Group__c WHERE id= :Recid];
            //system.debug('List'+abc);                      
            }
        }
          delete abc1;          
        return null;
    }   
    public class wrapGroup{
        public Group__c gname{get;set;}
            public boolean checkbox1{get;set;}       
    public wrapGroup(Group__c g){
        gname=g;
        checkbox1=false;
    }     
    }
 }


 
<apex:page controller="Task0" >
    <apex:form >
       <script>
         function enableDisable(cb)
    {
      $("input:checkbox[id*=looped]").removeAttr('checked');
      $(cb).attr('checked', 'checked');
    }
		</script>
        <apex:pageBlock >
            <!--<apex:commandButton value="Delete" action="{!Del}" />-->
            <apex:pageBlockTable value="{!acc}" var="a" >
                <apex:column value="{!a.gname.name}"/>
                <apex:column value="{!a.gname.Mobile__c}"/>
                <apex:column value="{!a.gname.Course_Name__c}"/>
               <!-- <apex:column >
                    <apex:outputField value="{!a.gname.Id}">
                <apex:param value="{!a.gname.id}" assignTo="{!Recid}" />  
                    </apex:outputField>
                </apex:column>-->
                <apex:column title="Select to Delete" >
                   
                 <apex:inputCheckbox id="looped" value="{!a.checkbox1}" onclick="enableDisable(this)" />                   
                        
                </apex:column>
               
            </apex:pageBlockTable>
         </apex:pageBlock>
     </apex:form>   
</apex:page>

 
I have a one custom field in Account object Called 'Rate__c' and My package Namespace is 'XYZ'. After installing package to any org; XYZ__Rate__c  field gets created . My requirement is to create field without namespace (only Rate__c).

 
Hi all,

We need to implement the following pattern at my org:
  • callout to external data source
  • if that callout takes too long (according to some configurable threshold), log an error (ie do some DML)
  • if that callout timed out on the remote server, try it again
Recognizing the potential for the dreaded "You have uncommitted work pending. Please commit or rollback before calling out." error, I put the error logging code in a future method, thus isolating the DML from the callouts. However, the error is still being thrown. I reduced the issue down to this pattern:
public static void foo() {
    Http http = new Http();
    HttpRequest req = new Httprequest();
    req.setEndpoint('https://test.salesforce.com'); //whatever endpoint
    req.setMethod('GET');
    http.send(req); //works fine
    bar();
    http.send(req); //throws calloutexception
}

@future public static void bar() {

}
Am I correct to assume that calling a future method counts as a DML operation? Is there any documentation I'm missing somewhere?

 
Hi,

I am retrieving the records from saleforce using bulk api. I created a job and added a batch to it. When I check the job status, saleforce gave me many batches associated to the job. I need to know how saleforce decides the total number of batches in a job for bulk api?