• Salesforce Developer 60
  • NEWBIE
  • 25 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 18
    Replies
This is my controller. Can anyone suggests me how to add test class for this controller. And one more question in this line AccountContactRole cont=new AccountContactRole(Role='None',ContactId='0032800000CIMN0', IsPrimary=false, AccountId=getAccount().id); am hardcode the contactId. So how to remove this from here.
public class AccountAndcontactrolesEditExtensionV2{
    private ApexPages.StandardController std;
     
    // the associated AccountContactRoles
   public List<AccountContactRole> AccountContactRoles;
      
    // the chosen AccountContactRole id - used when deleting a AccountContactRole
    public Id chosenAccountContactRoleId {get; set;}
     
    public AccountAndcontactrolesEditExtensionV2(ApexPages.StandardController stdCtrl)
    {
     std=stdCtrl;
    }
     
    public Account getAccount()
    {
     return (Account) std.getRecord();
    }
 
    private boolean updateAccountContactRoles()
    {
        boolean result=true;
        if (null!=AccountContactRoles)
           {
           List<AccountContactRole> updConts=new List<AccountContactRole>();
              try
              {
               update AccountContactRoles;
              }
              catch (Exception e)
              {
                 String msg=e.getMessage();
                 integer pos;
                  
                 // if its field validation, this will be added to the messages by default
                 if (-1==(pos=msg.indexOf('FIELD_CUSTOM_VALIDATION_EXCEPTION, ')))
                 {
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, msg));
                 }
                  
                 result=false;
              }
           }
            
           return result;
    }
     
    public PageReference saveAndExit()
    {
     boolean result=true;
    result=updateAccountContactRoles();
      
     if (result)
     {
        // call standard controller save
        return std.save();
     }
     else
     {
      return null;
     }
    }
     
    public PageReference save()
    {
     Boolean result=true;
     PageReference pr=Page.contactRole2;
     if (null!=getAccount().id)
     {
      result=updateAccountContactRoles();
     }
     else
     {
      pr.setRedirect(true);
     }
      
     if (result)
     {
        // call standard controller save, but don't capture the return value which will redirect to view page
        std.save();
           ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Changes saved'));
     }
        pr.getParameters().put('id', getAccount().id);
      
     return pr;
    }
 
    public void newAccountContactRole()
    {
       if (updateAccountContactRoles())
       {
          AccountContactRole cont=new AccountContactRole(Role='None',ContactId='0032800000CIMN0', IsPrimary=false, AccountId=getAccount().id);
          insert cont;
         
          // null the AccountContactRoles list so that it is rebuilt
          AccountContactRoles=null;
       }
    }
     
    public void deleteAccountContactRole()
    {
       if (updateAccountContactRoles())
       {
          if (null!=chosenAccountContactRoleId)
          {
             AccountContactRole cont=new AccountContactRole(Id=chosenAccountContactRoleId);
              delete cont;
        
           // null the AccountContactRoles list so that it is rebuilt
              AccountContactRoles=null;
              chosenAccountContactRoleId=null;
          }
       }
    }
     
   public List<AccountContactRole> getAccountContactRoles()
    {
       if ( (null!=getAccount().id) && (AccountContactRoles == null) )
       {
           AccountContactRoles=[SELECT Id,Role,AccountId,IsPrimary,ContactId
                         FROM AccountContactRole 
                         WHERE AccountId = : getAccount().ID
                         ORDER BY CreatedDate];
       }
                           
       return AccountContactRoles;
    }
}

 
Hello Team ,
                  I created below api class and it's test class but am getting 21% test coverage how to increase this test coverage?

This is my api class
 
public class ClientRepository {

    public ClientRepository(ApexPages.StandardController controller) {

    }

    public String message {get; set;}
    //public String input{get;set;}
    
    public PageReference GetInvoiceSummary( ) { 
        string accesstoken;
        InvoiceSummaryDetail invoiceDetail = new InvoiceSummaryDetail();
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        Id accId= Apexpages.currentPage().getParameters().get('Id');
        Account acc=[select id,CRXIS_Client_ID__c from Account where Id=:accId];
         String strId = Id.valueOf(acc.Id);
        
        if(acc.CRXIS_Client_ID__c !=null)
        {
        
                Integer ClientId =integer.valueof(acc.CRXIS_Client_ID__c);
                system.debug(ClientId );
                SessionData__c objToken = [select Access_Token1__c,Access_Token2__c,Access_Token3__c from SessionData__c where Name='token2'];
                 accesstoken =objToken.Access_Token1__c+objToken.Access_Token2__c+objToken.Access_Token3__c;
                system.debug(accesstoken);
                req.setHeader('Authorization','Bearer '+accesstoken);
                req.setMethod('GET');
                req.setEndpoint('http://google.com/?ClientID='+ClientId);
        
                try {
                     res = http.send(req);
                   
                     message =  res.getBody();
                     invoiceDetail = (InvoiceSummaryDetail)JSON.deserialize(message, InvoiceSummaryDetail.class);
        
                     System.debug(invoiceDetail);
                     System.debug(res.getBody());
                    
               
            
    
   List<Invoice__c> objInvo =[Select Name,Customer__c,InvoiceID__c FROM Invoice__c where Customer__c=:acc.Id]; 
          
         
          system.debug(objInvo.size());  
               if(objInvo.size()<=0){
List<Invoice__c> invoiceList = new List<Invoice__c>();

   
               
for(InvoiceSummary iData:invoiceDetail.ListInvoiceSummary)
{    Invoice__c objInvoice=new Invoice__c();   
    objInvoice.Customer__c =acc.Id;  
        /*System.debug(iData.InvoiceAmount);*/
    objInvoice.BalanceDue__c=iData.BalanceDue;
    objInvoice.InvoiceID__c=iData.InvoiceId;
    objInvoice.InvoiceAmount__c=iData.InvoiceAmount;
    date parsedDate = date.parse(iData.InvoiceDate);
    Integer years =parsedDate.year();
    objInvoice.InvoiceYear__c =string.valueof(years) ;
   objInvoice.InvoiceDate__c=parsedDate;
    objInvoice.InvoiceNumber__c=iData.InvoiceNumber;
    objInvoice.InvoiceType__c=iData.InvoiceType;
    objInvoice.TotalCases__c=iData.TotalCase;
    invoiceList.add(objInvoice);
  
}

  insert invoiceList;
               }
               else{
               
               system.debug('Already Invoice');
               }


            
        
          } catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
            message = res.getBody();
            System.debug(res.getBody());
          }
          }
            return null;
        
  }

}

This is my mockcallout class
 
@isTest
global class MockHttpResponseGeneratorInvoice implements HttpCalloutMock {
   // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
          String accesstoken ='3YWiojf9Qe88XSLrlZrZZqlKPg8NWanYrs1kDy0M_8tWXeO8e4u0cmnTdePUa9lfhoDRikUmXqgCh_hwD6Sv_gJTx3rOu0fPUSpMX8vIeuuzeAUX27cY897ZtAh-WSnwxzlMOQ5jFcuDZWadL5FM6F4OgAaSwyxRHSBoKvp9lU7M0fPaEiN-5E1iX3n1D3BLPzb3CUBtlfrKAzCBQB4gWj_lF4ggFCtTVPvXHhTKqWxYjc7czW83DhoQDJa2vqeYKGHHex_X77n_K4N-ASZzJhjJvG_F7u6mTdTOBlxsBpb_SgFsvLMmPl2aIyoz_-C341VDkKShObWBuXULaLTM0O4n64IrRiwGbIhq4Eh9SAmnkGTjSljPexEWnJMfSW_6fa9Qj2HKw7OyleFVcZYfTNFx_rmeDawAvGOhoZdNREl5bqNHY3RbEFSArgrI0onp0YFk2KePK5YFj-q-NiZvkh2ZruLY3GB1fFNbNTaVAGkXkp9b0vA8ReLk_Cuji6av';
        req.setHeader('Authorization','Bearer '+ accesstoken);
        
        System.assertEquals('http://google.com/GetInvoiceSummary?ClientID='+12, req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
  
       // Create a fake response
        HttpResponse res = new HttpResponse();
       // res2.setHeader('Content-Type', 'application/json');
       // res2.setStatusCode(200);
        res.setBody('{"ClientId":12,"ClientName":"Nrt","ListInvoiceSummary":[{"InvoiceId":1,"InvoiceNumber":"10031","InvoiceDate":"6/27/2008","InvoiceType":"Full Paid","InvoiceTypeId":null,"IsFullPaid":true,"InvoiceAmount":"12","BalanceDue":0.0,"TotalCase":1},{"InvoiceId":2,"InvoiceNumber":"10036","InvoiceDate":"7/30/2008","InvoiceType":"Full Paid","InvoiceTypeId":null,"IsFullPaid":true,"InvoiceAmount":"16","BalanceDue":0.0,"TotalCase":1}]}');
        
        system.debug(res.getBody());
        return res;
    }
This is my callouttest class
 
@isTest
private class CalloutClassTest2 {
public CalloutClassTest2(){
        }
     @isTest static void testCallout2() {
       // Set mock callout class
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGeneratorInvoice());  
       // Call method to test.
        // This causes a fake response to be sent from the class that implements HttpCalloutMock.
        Account a = new Account();
        a.Name = 'Test';
        a.CRXIS_Client_ID__c ='30';
        insert a;
        
        Invoice__c inv = new Invoice__c();
        //inv.Name ='test';
        inv.Customer__c ='001280000035FQG';
        inv.InvoiceID__c  ='001280000035FQG';
        insert inv;
        
        ApexPages.CurrentPage().getparameters().put('id', a.id);
        ApexPages.StandardController sc = new ApexPages.standardController(a); 
        ClientRepository w = new ClientRepository (sc);
        ClientRepository con = New ClientRepository (New ApexPages.StandardController(a));
        con.GetInvoiceSummary();
        
        
    }
}


 
Hello Team,
                  I created following class now i want to schedule this class to run daily at 10 AM . I already created a scheduler class and it schedule correctly but when it run it will give error like arguments not be null .

Here is my webservice class.
 
public with sharing class WebserviceCall {

    public WebserviceCall(ApexPages.StandardController controller) {

    }

    public String message {get; set;}
    
    public PageReference getaccesstoken() { 
      string jsonstring ='userName=test@gmail.com&Password=123&grant_type=password';
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
       // req.setClientCertificateName('Client Certificate');
       
        req.setEndpoint('http://google.com');
        req.setMethod('POST');
       // req.setHeader('SOAPAction', 'Soap Action');
        //req.setHeader('Authorization','Auth Token');
      
       req.setBody(jsonstring);
 
           try {
            res = http.send(req);
            message = res.getBody();
    TokenInformation token = new TokenInformation();
    token =(TokenInformation)System.JSON.deserialize(message, TokenInformation.class);
  // JSONParser parser = JSON.createParser(res.getBody());
            System.debug(token.access_token);
                 //HttpServletResponse httpResponse = (HttpServletResponse)response;
              string s = token.access_token;
            string a1 = s.substring(0,255);
            string a2 = s.substring(255,510);
            string a3 =s.substring (510,s.length());
            //Here SessionData__c is custom setting used for store access_token
       SessionData__c objToken = new SessionData__c();
       objToken.Name ='token2';
       objToken.Id ='a0G28000000ENAI';
    objToken.Access_Token1__c =a1;objToken.Access_Token2__c =a2;
               objToken.Access_Token3__c =a3;

upsert objToken;
               
        } catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
             message = res.toString() + res.getBody();
            System.debug(res.toString());
        }
        return null;
        
}       
    
    
    
    
}

here is Scheduler class
 
global class scheduledWebServiceCall implements Schedulable {
    
   global void execute(SchedulableContext sc) {
   Account acc = new Account();
   Apexpages.Standardcontroller controller_inv = new Apexpages.Standardcontroller(acc);
      WebserviceCall b = new WebserviceCall(controller_inv); 
      b.getaccesstoken();
      
       system.debug( b.getaccesstoken());
   }
}

 
Hello ,
         I create a webservice for consuming rest api from .net . I am facing issue in test class for this . It's gives error callout not allowed from test method. How to write test class for below controller.
 
public with sharing class WebserviceCall {

    public WebserviceCall(ApexPages.StandardController controller) {

    }

    public String message {get; set;}
    
    public PageReference getaccesstoken() { 
      string jsonstring ='userName=test@gmail.com&Password=123&grant_type=password';
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
       // req.setClientCertificateName('Client Certificate');
       
        req.setEndpoint('http://google.com');
        req.setMethod('POST');
       // req.setHeader('SOAPAction', 'Soap Action');
        //req.setHeader('Authorization','Auth Token');
      
       req.setBody(jsonstring);
 
           try {
            res = http.send(req);
            message = res.getBody();
    TokenInformation token = new TokenInformation();
    token =(TokenInformation)System.JSON.deserialize(message, TokenInformation.class);
  // JSONParser parser = JSON.createParser(res.getBody());
            System.debug(token.access_token);
                 //HttpServletResponse httpResponse = (HttpServletResponse)response;
              string s = token.access_token;
            string a1 = s.substring(0,255);
            string a2 = s.substring(255,510);
            string a3 =s.substring (510,s.length());
            //Here SessionData__c is custom setting used for store access_token
       SessionData__c objToken = new SessionData__c();
       objToken.Name ='token2';
       objToken.Id ='a0G28000000ENAI';
    objToken.Access_Token1__c =a1;objToken.Access_Token2__c =a2;
               objToken.Access_Token3__c =a3;

upsert objToken;
               
        } catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
             message = res.toString() + res.getBody();
            System.debug(res.toString());
        }
        return null;
        
}       
    
    
    
    
}

Hi Team,
             I created a  dynamic search controller for search dynamically in visualforce page . How to write test class for this type controller.

This is my controller code.Please help me how to write test class for this controller.
public with sharing class ContactSearchController {

  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Contact> contacts {get;set;}

  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'lastName'; } return sortField;  }
    set;
  }

  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public ContactSearchController() {
  contacts= new List<Contact>();
    soql = 'select FirstName, LastName,account.name,LeadSource FROM Contact Where account.Name!=null';
    runQuery();
  }

  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      contacts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {
      
    String FirstName = Apexpages.currentPage().getParameters().get('FirstName');
    String LastName = Apexpages.currentPage().getParameters().get('LastName');
   
    String LeadSource = Apexpages.currentPage().getParameters().get('LeadSource ');
    
    String accountName= Apexpages.currentPage().getParameters().get('accountName');
   
  

    soql = 'select  FirstName,LastName,LeadSource,account.name FROM Contact Where account.Name!=null';
   
    if (FirstName!= null && !FirstName.equals(''))
      soql += ' and FirstName LIKE \''+String.escapeSingleQuotes(FirstName)+'%\'';
    if (LastName!= null && !LastName.equals(''))
      soql += ' and LastName LIKE \''+String.escapeSingleQuotes(LastName)+'%\'';
    if (accountName!= null && !accountName.equals(''))
      soql += ' and account.Name LIKE \''+String.escapeSingleQuotes(accountName)+'%\'';
    if (LeadSource !=null && !LeadSource.equals(''))
      soql += ' and LeadSource LIKE \''+String.escapeSingleQuotes(LeadSource)+'%\'';  
  
    // run the query again
    runQuery();

    return null;
  }
 public List<String> LeadSource{
    get {
      if (LeadSource== null) {
 
        LeadSource= new List<String>();
        Schema.DescribeFieldResult field = Contact.LeadSource.getDescribe();
 
        for (Schema.PicklistEntry b : field.getPicklistValues())
          LeadSource.add(b.getLabel());
 
      }
      return LeadSource;          
    }
    set;
  }
 
}

 
Hi,
  I am new to Salesforce API. Currently i am working on calling .net rest api into salesforce. I am able to hit the url and get access token in developer console but now i want to store this into cookie for use in future call. Any sample code for consume .net Api into saleforce using store access token into cookies? I already register api url into remote setting , I have doubt should i register it into connected app also?

Thanks
This is my controller. Can anyone suggests me how to add test class for this controller. And one more question in this line AccountContactRole cont=new AccountContactRole(Role='None',ContactId='0032800000CIMN0', IsPrimary=false, AccountId=getAccount().id); am hardcode the contactId. So how to remove this from here.
public class AccountAndcontactrolesEditExtensionV2{
    private ApexPages.StandardController std;
     
    // the associated AccountContactRoles
   public List<AccountContactRole> AccountContactRoles;
      
    // the chosen AccountContactRole id - used when deleting a AccountContactRole
    public Id chosenAccountContactRoleId {get; set;}
     
    public AccountAndcontactrolesEditExtensionV2(ApexPages.StandardController stdCtrl)
    {
     std=stdCtrl;
    }
     
    public Account getAccount()
    {
     return (Account) std.getRecord();
    }
 
    private boolean updateAccountContactRoles()
    {
        boolean result=true;
        if (null!=AccountContactRoles)
           {
           List<AccountContactRole> updConts=new List<AccountContactRole>();
              try
              {
               update AccountContactRoles;
              }
              catch (Exception e)
              {
                 String msg=e.getMessage();
                 integer pos;
                  
                 // if its field validation, this will be added to the messages by default
                 if (-1==(pos=msg.indexOf('FIELD_CUSTOM_VALIDATION_EXCEPTION, ')))
                 {
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, msg));
                 }
                  
                 result=false;
              }
           }
            
           return result;
    }
     
    public PageReference saveAndExit()
    {
     boolean result=true;
    result=updateAccountContactRoles();
      
     if (result)
     {
        // call standard controller save
        return std.save();
     }
     else
     {
      return null;
     }
    }
     
    public PageReference save()
    {
     Boolean result=true;
     PageReference pr=Page.contactRole2;
     if (null!=getAccount().id)
     {
      result=updateAccountContactRoles();
     }
     else
     {
      pr.setRedirect(true);
     }
      
     if (result)
     {
        // call standard controller save, but don't capture the return value which will redirect to view page
        std.save();
           ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Changes saved'));
     }
        pr.getParameters().put('id', getAccount().id);
      
     return pr;
    }
 
    public void newAccountContactRole()
    {
       if (updateAccountContactRoles())
       {
          AccountContactRole cont=new AccountContactRole(Role='None',ContactId='0032800000CIMN0', IsPrimary=false, AccountId=getAccount().id);
          insert cont;
         
          // null the AccountContactRoles list so that it is rebuilt
          AccountContactRoles=null;
       }
    }
     
    public void deleteAccountContactRole()
    {
       if (updateAccountContactRoles())
       {
          if (null!=chosenAccountContactRoleId)
          {
             AccountContactRole cont=new AccountContactRole(Id=chosenAccountContactRoleId);
              delete cont;
        
           // null the AccountContactRoles list so that it is rebuilt
              AccountContactRoles=null;
              chosenAccountContactRoleId=null;
          }
       }
    }
     
   public List<AccountContactRole> getAccountContactRoles()
    {
       if ( (null!=getAccount().id) && (AccountContactRoles == null) )
       {
           AccountContactRoles=[SELECT Id,Role,AccountId,IsPrimary,ContactId
                         FROM AccountContactRole 
                         WHERE AccountId = : getAccount().ID
                         ORDER BY CreatedDate];
       }
                           
       return AccountContactRoles;
    }
}

 
Hello Team ,
                  I created below api class and it's test class but am getting 21% test coverage how to increase this test coverage?

This is my api class
 
public class ClientRepository {

    public ClientRepository(ApexPages.StandardController controller) {

    }

    public String message {get; set;}
    //public String input{get;set;}
    
    public PageReference GetInvoiceSummary( ) { 
        string accesstoken;
        InvoiceSummaryDetail invoiceDetail = new InvoiceSummaryDetail();
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        Id accId= Apexpages.currentPage().getParameters().get('Id');
        Account acc=[select id,CRXIS_Client_ID__c from Account where Id=:accId];
         String strId = Id.valueOf(acc.Id);
        
        if(acc.CRXIS_Client_ID__c !=null)
        {
        
                Integer ClientId =integer.valueof(acc.CRXIS_Client_ID__c);
                system.debug(ClientId );
                SessionData__c objToken = [select Access_Token1__c,Access_Token2__c,Access_Token3__c from SessionData__c where Name='token2'];
                 accesstoken =objToken.Access_Token1__c+objToken.Access_Token2__c+objToken.Access_Token3__c;
                system.debug(accesstoken);
                req.setHeader('Authorization','Bearer '+accesstoken);
                req.setMethod('GET');
                req.setEndpoint('http://google.com/?ClientID='+ClientId);
        
                try {
                     res = http.send(req);
                   
                     message =  res.getBody();
                     invoiceDetail = (InvoiceSummaryDetail)JSON.deserialize(message, InvoiceSummaryDetail.class);
        
                     System.debug(invoiceDetail);
                     System.debug(res.getBody());
                    
               
            
    
   List<Invoice__c> objInvo =[Select Name,Customer__c,InvoiceID__c FROM Invoice__c where Customer__c=:acc.Id]; 
          
         
          system.debug(objInvo.size());  
               if(objInvo.size()<=0){
List<Invoice__c> invoiceList = new List<Invoice__c>();

   
               
for(InvoiceSummary iData:invoiceDetail.ListInvoiceSummary)
{    Invoice__c objInvoice=new Invoice__c();   
    objInvoice.Customer__c =acc.Id;  
        /*System.debug(iData.InvoiceAmount);*/
    objInvoice.BalanceDue__c=iData.BalanceDue;
    objInvoice.InvoiceID__c=iData.InvoiceId;
    objInvoice.InvoiceAmount__c=iData.InvoiceAmount;
    date parsedDate = date.parse(iData.InvoiceDate);
    Integer years =parsedDate.year();
    objInvoice.InvoiceYear__c =string.valueof(years) ;
   objInvoice.InvoiceDate__c=parsedDate;
    objInvoice.InvoiceNumber__c=iData.InvoiceNumber;
    objInvoice.InvoiceType__c=iData.InvoiceType;
    objInvoice.TotalCases__c=iData.TotalCase;
    invoiceList.add(objInvoice);
  
}

  insert invoiceList;
               }
               else{
               
               system.debug('Already Invoice');
               }


            
        
          } catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
            message = res.getBody();
            System.debug(res.getBody());
          }
          }
            return null;
        
  }

}

This is my mockcallout class
 
@isTest
global class MockHttpResponseGeneratorInvoice implements HttpCalloutMock {
   // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
          String accesstoken ='3YWiojf9Qe88XSLrlZrZZqlKPg8NWanYrs1kDy0M_8tWXeO8e4u0cmnTdePUa9lfhoDRikUmXqgCh_hwD6Sv_gJTx3rOu0fPUSpMX8vIeuuzeAUX27cY897ZtAh-WSnwxzlMOQ5jFcuDZWadL5FM6F4OgAaSwyxRHSBoKvp9lU7M0fPaEiN-5E1iX3n1D3BLPzb3CUBtlfrKAzCBQB4gWj_lF4ggFCtTVPvXHhTKqWxYjc7czW83DhoQDJa2vqeYKGHHex_X77n_K4N-ASZzJhjJvG_F7u6mTdTOBlxsBpb_SgFsvLMmPl2aIyoz_-C341VDkKShObWBuXULaLTM0O4n64IrRiwGbIhq4Eh9SAmnkGTjSljPexEWnJMfSW_6fa9Qj2HKw7OyleFVcZYfTNFx_rmeDawAvGOhoZdNREl5bqNHY3RbEFSArgrI0onp0YFk2KePK5YFj-q-NiZvkh2ZruLY3GB1fFNbNTaVAGkXkp9b0vA8ReLk_Cuji6av';
        req.setHeader('Authorization','Bearer '+ accesstoken);
        
        System.assertEquals('http://google.com/GetInvoiceSummary?ClientID='+12, req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
  
       // Create a fake response
        HttpResponse res = new HttpResponse();
       // res2.setHeader('Content-Type', 'application/json');
       // res2.setStatusCode(200);
        res.setBody('{"ClientId":12,"ClientName":"Nrt","ListInvoiceSummary":[{"InvoiceId":1,"InvoiceNumber":"10031","InvoiceDate":"6/27/2008","InvoiceType":"Full Paid","InvoiceTypeId":null,"IsFullPaid":true,"InvoiceAmount":"12","BalanceDue":0.0,"TotalCase":1},{"InvoiceId":2,"InvoiceNumber":"10036","InvoiceDate":"7/30/2008","InvoiceType":"Full Paid","InvoiceTypeId":null,"IsFullPaid":true,"InvoiceAmount":"16","BalanceDue":0.0,"TotalCase":1}]}');
        
        system.debug(res.getBody());
        return res;
    }
This is my callouttest class
 
@isTest
private class CalloutClassTest2 {
public CalloutClassTest2(){
        }
     @isTest static void testCallout2() {
       // Set mock callout class
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGeneratorInvoice());  
       // Call method to test.
        // This causes a fake response to be sent from the class that implements HttpCalloutMock.
        Account a = new Account();
        a.Name = 'Test';
        a.CRXIS_Client_ID__c ='30';
        insert a;
        
        Invoice__c inv = new Invoice__c();
        //inv.Name ='test';
        inv.Customer__c ='001280000035FQG';
        inv.InvoiceID__c  ='001280000035FQG';
        insert inv;
        
        ApexPages.CurrentPage().getparameters().put('id', a.id);
        ApexPages.StandardController sc = new ApexPages.standardController(a); 
        ClientRepository w = new ClientRepository (sc);
        ClientRepository con = New ClientRepository (New ApexPages.StandardController(a));
        con.GetInvoiceSummary();
        
        
    }
}


 
Hello Team,
                  I created following class now i want to schedule this class to run daily at 10 AM . I already created a scheduler class and it schedule correctly but when it run it will give error like arguments not be null .

Here is my webservice class.
 
public with sharing class WebserviceCall {

    public WebserviceCall(ApexPages.StandardController controller) {

    }

    public String message {get; set;}
    
    public PageReference getaccesstoken() { 
      string jsonstring ='userName=test@gmail.com&Password=123&grant_type=password';
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
       // req.setClientCertificateName('Client Certificate');
       
        req.setEndpoint('http://google.com');
        req.setMethod('POST');
       // req.setHeader('SOAPAction', 'Soap Action');
        //req.setHeader('Authorization','Auth Token');
      
       req.setBody(jsonstring);
 
           try {
            res = http.send(req);
            message = res.getBody();
    TokenInformation token = new TokenInformation();
    token =(TokenInformation)System.JSON.deserialize(message, TokenInformation.class);
  // JSONParser parser = JSON.createParser(res.getBody());
            System.debug(token.access_token);
                 //HttpServletResponse httpResponse = (HttpServletResponse)response;
              string s = token.access_token;
            string a1 = s.substring(0,255);
            string a2 = s.substring(255,510);
            string a3 =s.substring (510,s.length());
            //Here SessionData__c is custom setting used for store access_token
       SessionData__c objToken = new SessionData__c();
       objToken.Name ='token2';
       objToken.Id ='a0G28000000ENAI';
    objToken.Access_Token1__c =a1;objToken.Access_Token2__c =a2;
               objToken.Access_Token3__c =a3;

upsert objToken;
               
        } catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
             message = res.toString() + res.getBody();
            System.debug(res.toString());
        }
        return null;
        
}       
    
    
    
    
}

here is Scheduler class
 
global class scheduledWebServiceCall implements Schedulable {
    
   global void execute(SchedulableContext sc) {
   Account acc = new Account();
   Apexpages.Standardcontroller controller_inv = new Apexpages.Standardcontroller(acc);
      WebserviceCall b = new WebserviceCall(controller_inv); 
      b.getaccesstoken();
      
       system.debug( b.getaccesstoken());
   }
}

 
Hello ,
         I create a webservice for consuming rest api from .net . I am facing issue in test class for this . It's gives error callout not allowed from test method. How to write test class for below controller.
 
public with sharing class WebserviceCall {

    public WebserviceCall(ApexPages.StandardController controller) {

    }

    public String message {get; set;}
    
    public PageReference getaccesstoken() { 
      string jsonstring ='userName=test@gmail.com&Password=123&grant_type=password';
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
       // req.setClientCertificateName('Client Certificate');
       
        req.setEndpoint('http://google.com');
        req.setMethod('POST');
       // req.setHeader('SOAPAction', 'Soap Action');
        //req.setHeader('Authorization','Auth Token');
      
       req.setBody(jsonstring);
 
           try {
            res = http.send(req);
            message = res.getBody();
    TokenInformation token = new TokenInformation();
    token =(TokenInformation)System.JSON.deserialize(message, TokenInformation.class);
  // JSONParser parser = JSON.createParser(res.getBody());
            System.debug(token.access_token);
                 //HttpServletResponse httpResponse = (HttpServletResponse)response;
              string s = token.access_token;
            string a1 = s.substring(0,255);
            string a2 = s.substring(255,510);
            string a3 =s.substring (510,s.length());
            //Here SessionData__c is custom setting used for store access_token
       SessionData__c objToken = new SessionData__c();
       objToken.Name ='token2';
       objToken.Id ='a0G28000000ENAI';
    objToken.Access_Token1__c =a1;objToken.Access_Token2__c =a2;
               objToken.Access_Token3__c =a3;

upsert objToken;
               
        } catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
             message = res.toString() + res.getBody();
            System.debug(res.toString());
        }
        return null;
        
}       
    
    
    
    
}

Hi Team,
             I created a  dynamic search controller for search dynamically in visualforce page . How to write test class for this type controller.

This is my controller code.Please help me how to write test class for this controller.
public with sharing class ContactSearchController {

  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Contact> contacts {get;set;}

  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'lastName'; } return sortField;  }
    set;
  }

  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public ContactSearchController() {
  contacts= new List<Contact>();
    soql = 'select FirstName, LastName,account.name,LeadSource FROM Contact Where account.Name!=null';
    runQuery();
  }

  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      contacts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {
      
    String FirstName = Apexpages.currentPage().getParameters().get('FirstName');
    String LastName = Apexpages.currentPage().getParameters().get('LastName');
   
    String LeadSource = Apexpages.currentPage().getParameters().get('LeadSource ');
    
    String accountName= Apexpages.currentPage().getParameters().get('accountName');
   
  

    soql = 'select  FirstName,LastName,LeadSource,account.name FROM Contact Where account.Name!=null';
   
    if (FirstName!= null && !FirstName.equals(''))
      soql += ' and FirstName LIKE \''+String.escapeSingleQuotes(FirstName)+'%\'';
    if (LastName!= null && !LastName.equals(''))
      soql += ' and LastName LIKE \''+String.escapeSingleQuotes(LastName)+'%\'';
    if (accountName!= null && !accountName.equals(''))
      soql += ' and account.Name LIKE \''+String.escapeSingleQuotes(accountName)+'%\'';
    if (LeadSource !=null && !LeadSource.equals(''))
      soql += ' and LeadSource LIKE \''+String.escapeSingleQuotes(LeadSource)+'%\'';  
  
    // run the query again
    runQuery();

    return null;
  }
 public List<String> LeadSource{
    get {
      if (LeadSource== null) {
 
        LeadSource= new List<String>();
        Schema.DescribeFieldResult field = Contact.LeadSource.getDescribe();
 
        for (Schema.PicklistEntry b : field.getPicklistValues())
          LeadSource.add(b.getLabel());
 
      }
      return LeadSource;          
    }
    set;
  }
 
}

 
Hi,
  I am new to Salesforce API. Currently i am working on calling .net rest api into salesforce. I am able to hit the url and get access token in developer console but now i want to store this into cookie for use in future call. Any sample code for consume .net Api into saleforce using store access token into cookies? I already register api url into remote setting , I have doubt should i register it into connected app also?

Thanks