Tuesday, 11 July 2017

'
 Code TO Parse XML  Using Apex Through DOM
public  class Xmlparsar
{
    //xml string
    public String xmlstring{get;set;}
  
    //display xml string
    public String outxmlstring{get;set;}
  
    //rootelement
    public String rootElement{get;set;}
  
    //
    public String filename{get;set;}
  
    public blob body{get;set;}
     
    //constructor
    public Xmlparsar()
    {
   
    }
  
   
//Parsing xml what you entered in the left text area
    public pagereference Parsexml()
    {
       DOM.Document xmlDOC = new DOM.Document();
       xmlDOC.load(xmlstring);
       DOM.XMLNode rootElement = xmlDOC.getRootElement();
       outxmlstring=String.valueof(xmlDOC.getRootElement().getName());
      
       for(DOM.XMLNode xmlnodeobj:xmlDOC.getRootElement().getChildElements())
       //.getChildren())
       {       
        
         if(xmlnodeobj.getChildElements().size()== 0)
          {
          outxmlstring+='\n'+xmlnodeobj.getName()+': '+xmlnodeobj.getText();
      
          }
          System.debug(xmlnodeobj);
          loadChilds(xmlnodeobj);        
       }
       
            
       return null;
    }
  
    //loading the child elements
    public void loadChilds(DOM.XMLNode xmlnode)
    {

        
         if(xmlnode.getChildElements().size()>0){
          outxmlstring+='\n'+xmlnode.getName();
        }
       
        for(Dom.XMLNode child : xmlnode.getChildElements())
        {
         
         
          if(child.getText()!= null)
          {
          outxmlstring+='\n'+child.getName()+': '+child.getText();
      
          }
          loadChilds(child);      
        }
        System.debug(xmlnode.getChildElements());
       
    
    }
  
  

}

VisualForce Page
<apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Parse Xml" action="{!Parsexml}" />  
            </apex:pageBlockButtons>
            <apex:inputTextArea value="{!xmlstring}" style="width:336px;height:260px;"/> &nbsp;&nbsp;
            <apex:inputTextArea value="{!outxmlstring}" style="width:336px;height:260px;" id="response"/><br/>
        </apex:pageBlock>
    </apex:form>







Wednesday, 28 June 2017

Insertion Sort

Start empty handed
Insert  a card in the right postion of the already sorted hand.
Continue until all cards are inserted/sorted.



Integer [] a=new Integer[]{50,11,23,10,20,30,40,10};

Integer n = a.size();
for (Integer i=1; i<n; ++i)
{
    Integer key = a[i];
    Integer j = i-1;

    /* Move elements of a[0..i-1], that are
    greater than key, to one position ahead
    of their current position */
    while (j>=0 && a[j] > key)
    {
        a[j+1] = a[j];
        j = j-1;
    }
    a[j+1] = key;
}

for (Integer i=0; i<n; ++i)
System.debug(a[i] + '  ');




Code in Apex to get Maximum Number from  an Array

                Integer [] a=new Integer[]{10,20,30,40};

                Integer currentMax=a[0];

                for(integer i =1;i<=a.size()-1;i++){
                   if(currentMax<a[i]){
                       currentMax=a[i];
                  }
                }


Friday, 15 July 2016

Code to Get All Parent and Child Object For A Give Object


Parent Object


Set<String> testName= new set<String>();

public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();

Map <String, Schema.SObjectField> fieldMap = schemaMap.get('Account').getDescribe().fields.getMap();
for(Schema.SObjectField sfield : fieldMap.Values())
{
schema.describefieldresult dfield = sfield.getDescribe();


if(dfield.getRelationshipName()!=null){
SObjectField sObjfieldName  =dfield.getSobjectField();
//System.debug(sObjfieldName  );
String abc=sObjfieldName  +'';

Map<String, Schema.SobjectField> fields = Account.getSObjectType().getDescribe().fields.getMap();

Schema.DescribeFieldResult f=fields.get(abc).getDescribe();



for(Schema.SObjectType reference : f.getReferenceTo()) {
testName.add(reference.getDescribe().getName());
}

}


}

for(String itr :testName){
System.debug(itr );
}


Child Object

// To Retrieve Sechma of the given Object
Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
// Reterieving relation ship field
List<Schema.ChildRelationship> C = R.getChildRelationships();
Set<String> abc= new Set<String>();
// iterating all the fields
for (Schema.ChildRelationship child : r.getChildRelationShips()) {
   // from field getting its sobject describe call
   Schema.DescribeSObjectResult childDesc = child.getChildSObject().getDescribe();
   // from that getting its name and passing in set
   abc.add(childDesc.getName());
}
for(String itr :abc){
System.debug(itr);
}

Wednesday, 11 March 2015

ENUM


An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Enums are typically
used to define a set of possible values that don’t otherwise have a numerical order, such as the suit of a card, or a particular season of
the year. Although each value corresponds to a distinct integer value, the enum hides this implementation so that you don’t inadvertently
misuse the values, such as using them to perform arithmetic. After you create an enum, variables, method arguments, and return types
can be declared of that type.


public enum Season {WINTER, SPRING, SUMMER, FALL}
Season e = Season.WINTER;

public Season m(Integer x, Season e1) {
if (e1 == Season.SUMMER) {
return Season.SUMMER;
}
else{
return Season.WINTER;
}
}

System.debug(m(1,Season.SUMMER));

Tuesday, 10 March 2015

Uniqueness of map keys of user-defined types is determined by the equals and hashCode methods,


public class PairNumbers {
    Integer x,y;

    public PairNumbers(Integer a, Integer b) {
        x=a;
        y=b;
    }

    public Boolean equals(Object obj) {
        if (obj instanceof PairNumbers) {
            PairNumbers p = (PairNumbers)obj;
            return ((x==p.x) && (y==p.y));
        }
        return false;
    }

    public Integer hashCode() {
        return (31 * x) * y;
    }
}

Use case:

Map<PairNumbers, String> m = new Map<PairNumbers, String>();
PairNumbers p1 = new PairNumbers(1,2);
PairNumbers p2 = new PairNumbers(3,4);
// Duplicate key
PairNumbers p3 = new PairNumbers(1,2);
PairNumbers p4 = new PairNumbers(2,1);

m.put(p1, 'first');
m.put(p2, 'second');
m.put(p3, 'third');
m.put(p4, 'third');


// Map size is 2 because the entry with 
// the duplicate key overwrote the first entry.
System.assertEquals(2, m.size());

// Use the == operator
if (p1 == p3) {
    System.debug('p1 and p3 are equal.');
}

// Perform some other operations
System.assertEquals(true, m.containsKey(p1));
System.assertEquals(true, m.containsKey(p2));
System.assertEquals(false, m.containsKey(new PairNumbers(5,6)));

for(PairNumbers pn : m.keySet()) {
    System.debug('Key: ' + pn);
}

List<String> mValues = m.values();
System.debug('m.values: ' + mValues);

// Create a set
Set<PairNumbers> s1 = new Set<PairNumbers>();
s1.add(p1);
s1.add(p2);
s1.add(p3);

// Verify that we have only two elements
// since the p3 is equal to p1.
System.assertEquals(2, s1.size());

Sunday, 15 February 2015

Common Trigger Problems


  1. Cascading Triggres
  2. Apex governor Limits
  3. Null Refernce errors
  4. Too many Soql 

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.

IsTest(OnInstall=true) Annotation

Use the IsTest(OnInstall=true) annotation to specify which Apex tests are executed during package installation. This annotation is used for tests in managed or unmanaged packages. Only test methods with this annotation, or methods that are part of a test class that has this annotation, will be executed during package installation. Tests annotated to run during package installation must pass in order for the package installation to succeed. It is no longer possible to bypass a failing test during package installation. A test method or a class that doesn't have this annotation, or that is annotated with isTest(OnInstall=false) or isTest, won't be executed during installation. This example shows how to annotate a test method that will be executed during package installation. In this example, test1 will be executed but test2 and test3 won't.




public class OnInstallClass {
// Implement logic for the class.
public void method1(){
// Some code
}
}
@isTest
private class OnInstallClassTest {
// This test method will be executed
// during the installation of the package.
@isTest(OnInstall=true)
static void test1() {
// Some test code
}
// Tests excluded from running during the
// the installation of a package.
82
Classes, Objects, and Interfaces IsTest Annotation
@isTest
static void test2() {
// Some test code
}
static testmethod void test3() {
// Some test code
}
}

Example shows how to apply the isTest(SeeAllData=true) annotation on a test method.

Because the class that the test method is contained in isn’t defined with this annotation, you have to apply this annotation on the test method to enable access to all data for that test method. The second test method doesn’t have this annotation, so it can access only the data it creates in addition to objects that are used to manage your organization, such as users.

// This class contains test methods with different data access levels.
@isTest
private class ClassWithDifferentDataAccess {
// Test method that has access to all data.
@isTest(SeeAllData=true)
static void testWithAllDataAccess() {
// Can query all data in the organization.
}
// Test method that has access to only the data it creates
// and organization setup and metadata objects.
@isTest static void testWithOwnDataAccess() {
// This method can still access the User object.
// This query returns the first user object.
User u = [SELECT UserName,Email FROM User LIMIT 1];
System.debug('UserName: ' + u.UserName);
System.debug('Email: ' + u.Email);
// Can access the test account that is created here.
Account a = new Account(Name='Test Account');
insert a;
// Access the account that was just created.
Account insertedAcct = [SELECT Id,Name FROM Account
WHERE Name='Test Account'];
System.assert(insertedAcct != null);
}
}

Considerations for the IsTest(SeeAllData=true) Annotation


• If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test
methods whether the test methods are defined with the @isTest annotation or the testmethod keyword.
• The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method level. However, using isTest(SeeAllData=false) on a method doesn’t restrict organization data access for that method if the containing class has already been defined with the isTest(SeeAllData=true) annotation. In this case, the method will still have access to all the data in the organization.

Sunday, 15 September 2013

Using the transient Keyword In salesforce

Use the transient keyword to declare instance variables that can't be saved, and shouldn't be transmitted as part of the view state for a Visualforce page. For example:

Transient Integer currentTotal;

You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions, or classes that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that define the types of fields declared in the serializable classes.

Declaring variables as transient reduces view state size. A common use case for the transient keyword is a field on a Visualforce page that is needed only for the duration of a page request, but should not be part of the page's view state and would use too many system resources to be recomputed many times during a request.

Some Apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view state. These objects include the following:
• PageReferences
• XmlStream classes
• Collections automatically marked as transient only if the type of object that they hold is automatically       marked as transient, such as a collection of Savepoints
• Most of the objects generated by system methods, such as Schema.getGlobalDescribe.
• JSONParser class instances. For more information, see JSON Support.

Static variables also don't get transmitted through the view state.

The following example contains both a Visualforce page and a custom controller. Clicking the refresh button on the page causes the transient date to be updated because it is being recreated each time the page is refreshed. The non-transient date continues to have its original value, which has been deserialized from the view state, so it remains the same.

Visual Force Page
<apex:page controller="ExampleController">
T1: {!t1} <br/>
T2: {!t2} <br/>
<apex:form>
<apex:commandLink value="refresh"/>
</apex:form>
</apex:page>

Controller

public class ExampleController {
DateTime t1;
transient DateTime t2;
public String getT1() {
if (t1 == null) t1 = System.now();
return '' + t1;
}
public String getT2() {
if (t2 == null) t2 = System.now();
101
Custom Controllers and Controller Extensions Using the transient Keyword
return '' + t2;
}
}

Thursday, 1 August 2013

Developing a Batch Apex Class




global class HelloBatchApex implements Database.Batchable<SObject> {



global Database.QueryLocator start(Database.BatchableContext context) {
System.debug('start');
return Database.getQueryLocator([SELECT Name FROM Proj__c ORDER BY Name]);
}


global void execute(Database.BatchableContext context,List<SObject> scope) {
       System.debug('execute');
for(SObject rec : scope) {
Proj__c p = (Proj__c)rec;
System.debug('Project: ' + p.Name);
}
}



global void finish(Database.BatchableContext context) {
System.debug('finish');
}



}

Wednesday, 19 June 2013


Page

The Visualforce page defines the appearance of your user interface using a mixture of
standard HTML and Visualforce-specific XML markup.The XML markup is used to add
view components to the page.View components bind the controller to the page, defining
how data and user actions are to be rendered in the user interface. Force.com provides a
standard set of view components to support common HTML user interface patterns and
supports user-defined components.
In Figure 7-1, the arrows between the page and the controller represent expressions.
Expressions are embedded in view components to allow the page to reference methods in
the controller or in system classes such as UserInfo. Expressions in Visualforce use the
same language as formula fields in the database, with a special prefix and suffix added. For
example, {!save} is an expression that invokes the save method of the controller.



Note
Visualforce maintains a strict separation of business logic and presentation. No business
logic is allowed in a Visualforce page, not even for trivial formatting tasks.