Sunday, 15 February 2015

Redirecting to a Standard Object List Page

For buttons or links that navigate a user to a standard tab, you can redirect the content to present a list of standard objects.

Create a Visualforce page with the following markup:


<apex:page action="{!URLFOR($Action.Account.List, $ObjectType.Account)}"/>

Custom Labels and Error Messages

When set, the label attribute will be used for component-level error messages, for example, when a field is required or must be unique. Custom labels won't be used in custom error messages, and the default object field label will be used instead. If you set a label attribute to an empty string, the default object field label will be used in all error messages

Sunday, 11 January 2015

Testing HTTP Callouts by Implementing the HttpCalloutMock Interface

global class MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('http://api.salesforce.com/foo/bar', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"foo":"bar"}');
        res.setStatusCode(200);
        return res;
    }
}
public class CalloutClass {
    public static HttpResponse getInfoFromExternalService() {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://api.salesforce.com/foo/bar');
        req.setMethod('GET');
        Http h = new Http();
        HttpResponse res = h.send(req);
        return res;
    }
}
@isTest
                        
private class CalloutClassTest {
     @isTest static void testCallout() {
        // Set mock callout class 
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        
        // Call method to test.
        // This causes a fake response to be sent
        // from the class that implements HttpCalloutMock. 
        HttpResponse res = CalloutClass.getInfoFromExternalService();
        
        // Verify response received contains fake values
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/json');
        String actualValue = res.getBody();
        String expectedValue = '{"foo":"bar"}';
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());
    }
}

Saturday, 10 January 2015

Testing SOSL


Use       Test.setFixedSearchResults


Class

public class MySearchClass{
    public Static void doSearch(String search){
        List<List<Sobject>> searchResult;
        searchResult=[FIND :search IN ALL FIELDS RETURNING Account];
        if(searchResult!=null){
            System.debug('in if'+searchResult);
            searchResult=[FIND :search IN ALL FIELDS RETURNING Account];
        }
        else{
            System.debug('in else'+searchResult);
            searchResult=[FIND :search IN ALL FIELDS RETURNING Account];
        }
    }
}

Test Class

@isTest
public class TestMySearchClass{
    private static testMethod void testMeth(){
        Account acc = new Account(Name='testBaljeet');
        insert acc;
        Test.setFixedSearchResults(new List<Id>{acc.id});
        MySearchClass.doSearch('test');
    }
}

Load TestData Using Static Resource CSV file in Test Class


@isTest
static testMethod void static_testResource(){
          List<sobject> cand=Test.loadData(Account.sObjectType,'testAccount');
}

Wednesday, 23 April 2014

Force.com Managed Sharing

Force.com managed sharing involves sharing access granted by Force.com based on record ownership, the role hierarchy,and sharing rules:

Record Ownership

Each record is owned by a user or optionally a queue for custom objects, cases and leads. The record owner is automatically granted Full Access, allowing them to view, edit, transfer, share, and delete the record.

Role Hierarchy

The role hierarchy enables users above another user in the hierarchy to have the same level of access to records owned by or shared with users below. Consequently, users above a record owner in the role hierarchy are also implicitly granted Full Access to the record, though this behavior can be disabled for specific custom objects. The role hierarchy is not maintained with sharing records. Instead, role hierarchy access is derived at runtime. For more information, see “Controlling Access Using Hierarchies” in the Salesforce online help.

Sharing Rules

Sharing rules are used by administrators to automatically grant users within a given group or role access to records owned by a specific group of users. Sharing rules cannot be added to a package and cannot be used to support sharing logic for apps installed from Force.com AppExchange.

Sharing rules can be based on record ownership or other criteria. You can’t use Apex to create criteria-based sharing rules. Also, criteria-based sharing cannot be tested using Apex.

All implicit sharing added by Force.com managed sharing cannot be altered directly using the Salesforce user interface, SOAP API, or Apex.

Wednesday, 1 January 2014

Setting Read-Only Mode for an Entire Page

To enable read-only mode for an entire page, set the readOnly attribute on the <apex:page> component to true.
For example, here is a simple page that will be processed in read-only mode:
<apex:page controller="SummaryStatsController" readOnly="true">
    <p>Here is a statistic: {!veryLargeSummaryStat}</p>
</apex:page>
The controller for this page is also simple, but illustrates how you can calculate summary statistics for display on a page:
public class SummaryStatsController {
    public Integer getVeryLargeSummaryStat() {
        Integer closedOpportunityStats = 
            [SELECT COUNT() FROM Opportunity WHERE Opportunity.IsClosed = true];
        return closedOpportunityStats;
    }
}
Normally, queries for a single Visualforce page request may not retrieve more than 50,000 rows. In read-only mode, this limit is relaxed to allow querying up to 1 million rows.
In addition to querying many more rows, the readOnly attribute also increases the maximum number of items in a collection that can be iterated over using components such as<apex:dataTable><apex:dataList>, and <apex:repeat>. This limit increased from 1,000 items to 10,000. Here is a simple controller and page demonstrating this:
public class MerchandiseController {

    public List<Merchandise__c> getAllMerchandise() {
        List<Merchandise__c> theMerchandise = 
            [SELECT Name, Price__c FROM Merchandise__c LIMIT 10000];
        return(theMerchandise);
    }
}
<apex:page controller="MerchandiseController" readOnly="true">
    <p>Here is all the merchandise we have:</p>
    <apex:dataTable value="{!AllMerchandise}" var="product">
        <apex:column>
            <apex:facet name="header">Product</apex:facet>
            <apex:outputText value="{!product.Name}" />
        </apex:column>
        <apex:column>
            <apex:facet name="header">Price</apex:facet>
            <apex:outputText value="{!product.Price__c}" />
        </apex:column>
    </apex:dataTable>
</apex:page>
While Visualforce pages that use read-only mode for the entire page can’t use data manipulation language (DML) operations, they can call getter, setter, and action methods which affect form and other user interface elements on the page, make additional read-only queries, and so on.