August 31, 2012

Steps to use external WSDL files in Salesforce

1. Get the WSDL. Save it in your local disk.

2. Go to Setup --> App Setup --> Develop --> Apex Classes.

3. Click 'Generate from WSDL'.


4. Browse and select the WSDL file saved in your local disk.


5. Parse the WSDL file.

6. Use the Apex class generated in your Salesforce application.


7. Set the End Point URL without fail.


Cheers!!!

Measures to make Software products more easily maintainable

  1. Always maintain simplicity in every aspect of your product – from the design, to implementation, even the software process.
  2. Stay organized in every part of the project.
  3. Proper documentation.
  4. Naming the class, variables, etc with proper naming conventions.
  5. Proper comments inside the code.
  6. Good indentation for code.
  7. Simpler codes.
  8. Avoid complex functionality.

Cheers!!!

August 30, 2012

Difference between Salesforce.com and Force.com

     Salesforce.com is Sales(CRM) and Service applications which were developed and running on the Force.com Platform. The developed applications will run on the force.com always as a multitenent architecture method. Simply you can identify Force.com is where you can access and customize your datamodel, bussiness logic and UserInterface. But in case of salesforce.com you can access the sales(CRM) Application with all the developed data model, Business logic and UserInterface. Since it is running on the force.com platform, you can customize your application funtionality.

     Force.com is based on the concept of Platform as a Service or commonly known as PAAS where as Salesforce.com is based on the concept of Application as a Service. So, we can say Salesforce.com is an application built by Salesforce on force.com platform and has been made available to people for use at per month per license pricing.

Cheers!!!

August 29, 2012

Component in Salesforce

In Salesforce component is a reusable piece of code developed using Visual force and Apex controller.

Example:

<!-- Page -->

<apex:page>

    <c:myComponent myValue="My component's value" borderColor="red" />

</apex:page>


<!-- Component:myComponent -->    

<apex:component>

    <apex:attribute name="myValue" description="This is the value for the component."  type="String" required="true"/>

    <apex:attribute name="borderColor" description="This is color for the border."  type="String" required="true"/>

    <h1 style="border:{!borderColor}">

        <apex:outputText value="{!myValue}"/>

    </h1>

</apex:component>


Cheers!!!

When to use triggers in Salesforce

Triggers are used to perform immediate actions based on the previous action.

If declarative workflows or Process Builders don’t meet your specific needs, then it’s time to turn to a programmatic approach using Apex, Force.com’s procedural language. Apex, very similar to Java, is akin to the procedural languages most database systems have to build stored procedures, database triggers, and unit tests that implement reliable, database-centralized, complex business logic. Here’s a quick look at some examples of how you can use Apex with Force.com.

Example: field update.

     A trigger is Apex code that executes before or after specific Data Manipulation Language (DML) events occur, such as before object records are inserted into the database, or after records have been deleted.

Syntax:

trigger triggerName on ObjectName (trigger_events)
{
    /*------------
    code_block
    -------------*/
}

where trigger_events can be a comma-separated list of one or more of the following events:
  1. before insert
  2. before update
  3. before delete
  4. after insert
  5. after update
  6. after delete
  7. after undelete

Difference between map and set in Salesforce

Set:
     A set is an unordered collection of primitives or sObjects that do not contain any duplicate elements.

Map:
     A map is a collection of key-value pairs where each unique key maps to a single value. Keys can be any primitive data type, while values can be a primitive, sObject, collection type or an Apex object.


Cheers!!!

August 24, 2012

VLOOKUP() example in Excel

Step 1: Enter data in sheet1.


Step 2: Enter data in Sheet2


Step 3: Enter the formula as '=VLOOKUP(A2,Sheet2!$A$2:$B$4,2)'


Step 4: Just drag it to other rows.


Cheers!!!

August 23, 2012

Salesforce openings

To know Salesforce openings, visit the below link

http://careers.force.com/jobs


Cheers!!!

Export using apex code in Salesforce

Export vf page:

<apex:page controller="ExportCtrlr">

<!-- Javascript -->

<script type="text/javascript">
function callFetchFields()
{
Fetch();
}
</script>
<!-- Javascript -->

<!-- CSS -->

<style type="text/css">
td
{
text-align:center;
}
</style>
<!-- CSS -->

<apex:form >


<apex:actionFunction name="Fetch" action="{!fetchFields}" reRender="entire"/>

<apex:pageblock id="entire">
<table cellspacing="15" cellpadding="10">
<tr>
<td><apex:outputLabel value="Select Object"/></td>
<td colspan="2">
<apex:selectList size="1" value="{!obj}" onChange="callFetchFields();">
<apex:selectOptions value="{!objs}"/>
</apex:selectList>
</td>
</tr>
<tr>
<td>
<apex:selectList size="6" multiselect="true" value="{!selFieldNames}" >
<apex:selectOptions value="{!soFieldNames}"/>
</apex:selectList>
</td>
<td>
<br/><apex:commandButton value=">>" action="{!addFields}" reRender="entire"/><br/><br/><br/>
<apex:commandButton value="<<" action="{!removeFields}" reRender="entire"/>
</td>
<td>
<apex:selectList size="6" multiselect="true" value="{!selAvaFieldNames}" >
<apex:selectOptions value="{!soAvailablefieldNames}"/>
</apex:selectList>
</td>
</tr>
<tr>
<td colspan="3"><apex:commandButton value="Export" action="{!exportFun}"/></td>
</tr>
</table>
</apex:pageblock>
</apex:form>
</apex:page>

ExportCtrlr apex code:

public class ExportCtrlr 
{
public Map<String, Schema.SObjectType> objs {get; set;}
public String obj {get;set;}
public List<String> objFields {get;set;}
public List<String> selFieldNames = new List<String>();
public List<String> selAvaFieldNames = new List<String>();
public List<String> availableFieldNames = new List<String>();
public String sql = '';

public ExportCtrlr()
{
objs = Schema.getGlobalDescribe();
List<Schema.Sobjecttype> temp = objs.values();
obj = String.valueOf(temp.get(0));
System.debug('First Object is ' + obj);
fetchFields();
}

public void fetchFields()
{
availableFieldNames.clear();
Map<String , Schema.SObjectType> globalDescription = Schema.getGlobalDescribe();
Schema.sObjectType objType = globalDescription.get(obj); 
Schema.DescribeSObjectResult r1 = objType.getDescribe(); 
Map<String , Schema.SObjectField> mapFieldList = r1.fields.getMap();
objFields = new List<String>();
        for(Schema.SObjectField field : mapFieldList.values())  
        {  
            Schema.DescribeFieldResult fieldResult = field.getDescribe();
            System.debug('Field Name is ' + fieldResult.getName());  
            if(fieldResult.isAccessible())  
            {  
                objFields.add(fieldResult.getName());
            }  
        }
        System.debug('Fields are ' + objFields);
}

public pageReference exportFun()
{
Integer i =0;
Integer len = availableFieldNames.size() - 1;
sql = 'SELECT ';
for(i = 0; i < availableFieldNames.size(); i++)
{
if(i != len)
{
sql = sql + availableFieldNames[i] + ',';
}
else
{
sql = sql + availableFieldNames[i] + ' FROM ' + obj;
}
}
System.debug('Selected Object is ' + obj);
pageReference pg = new pageReference('/apex/ExportAsCSV?objName='+obj+'&soql='+sql);
pg.setRedirect(true);
return pg;
}

public List<SelectOption> getsoFieldNames()    
    {          
         List<SelectOption> options = new List<SelectOption>();
         for(String temp:objFields)
         {     
         options.add(new SelectOption(temp,temp));
         }      
         return options;    
    }
    
public List<SelectOption> getsoAvailablefieldNames()    
    {          
         List<SelectOption> options = new List<SelectOption>();
         for(String tmp:selFieldNames)
         {
          availableFieldNames.add(tmp);
         }
         for(String temp:availableFieldNames)
         {     
         options.add(new SelectOption(temp,temp));
         }      
         selFieldNames.clear();
         return options;    
    }   
    
     public List<String> getselFieldNames()     
     {      
         return selFieldNames;    
     }        
     public void setselFieldNames(List<String> selFieldNames)     
     {      
         this.selFieldNames = selFieldNames;    
     } 
     
     public List<String> getselAvaFieldNames()     
     {      
         return selAvaFieldNames;    
     }        
     public void setselAvaFieldNames(List<String> selAvaFieldNames)     
     {      
         this.selAvaFieldNames = selAvaFieldNames; 
     }
     
     public void addFields()
     {
      Integer i = 0;
      for(String tmp:selFieldNames)
         {
             selAvaFieldNames.add(tmp);
             for(i = 0; i<objFields.size(); i++)
             {
                 if(objFields[i] == tmp)
                 {
                     objFields.remove(i);
                 }
             }                          
         }    
     }
     
     public void removeFields()
     {
      Integer i = 0;
      for(String tmp:selAvaFieldNames)
         {
             objFields.add(tmp);
             for(i = 0; i<availableFieldNames.size(); i++)
             {
                 if(availableFieldNames[i] == tmp)
                 {
                     availableFieldNames.remove(i);
                 }
             }                          
         }
     }
}

ExportAsCSV vf Page:

<apex:page controller="ExportAsCSV" action="{!exportToCSV}" cache="true" contentType="application/vnd.ms-excel#export.csv" language="en-US">
{!fieldNames}{!newLine}<apex:repeat value="{!objLst}" var="object"><apex:repeat value="{!flds}" var="field">{!object[field]}{!coma}</apex:repeat>{!newLine}</apex:repeat>
</apex:page>


ExportAsCSV Apex Code:

public class ExportAsCSV 
{
public List<sObject> objLst {get;set;}
public String obj;
public String soql;
public String fieldNames {get;set;}
public List<String> flds {get;set;}
public String coma {get;set;}
public String newLine {get;set;}

public ExportAsCSV()
{
coma = ',';
newLine = '\n';
obj = System.currentPageReference().getParameters().get('objName');
soql = System.currentPageReference().getParameters().get('soql');
System.debug('Selected Object is ' + obj);
}

public void exportToCSV()
{
fieldNames = soql.subString(7,soql.indexOf(' FROM'));
flds = fieldNames.split(',');
  objLst = Database.Query(soql);
}
}

August 22, 2012

How to get fields for sObject using Apex?

Sample Code:

       public String obj {get;set;} public List<sObject> objLst {get;set;} 
       public List<String> objFields {get;set;}
       Map<String , Schema.SObjectType> globalDescription = Schema.getGlobalDescribe();
  Schema.sObjectType objType = globalDescription.get(obj); 
  Schema.DescribeSObjectResult r1 = objType.getDescribe(); 
  Map<String , Schema.SObjectField> mapFieldList = r1.fields.getMap();  

        for(Schema.SObjectField field : mapFieldList.values())  

        {  
            Schema.DescribeFieldResult fieldResult = field.getDescribe();  
            if(fieldResult.isAccessible())  
            {  
                objFields.add(fieldResult.getName());
            }  
        }


Cheers!!!

URL No Longer Exists. You have attempted to reach a URL that no longer exists on salesforce.com error.

In order to overcome 'URL No Longer Exists. You have attempted to reach a URL that no longer exists on salesforce.com' error, avoid using '/' at the end of the URL.

Correct Code:

pageReference pg = new pageReference('/apex/ExportAsCSV');
pg.setRedirect(true);
return pg;


Incorrect Code:

pageReference pg = new pageReference('/apex/ExportAsCSV/');
pg.setRedirect(true);
return pg;

'/' should not come at the end.


Cheers!!!

August 17, 2012

Example for System.debug() in Salesforce

The main use of System.debug() is to track the flow of program and find errors.

Example:

  parsedCSVdata = parseCSV(fileString,false);
System.debug('Parsed CSV Data -->' + parsedCSVdata);

To see this go to Setup --> Administration Setup --> Monitoring --> Debug Log
Assign the user and execute the Apex code. Then refresh the debug log page and click view button.




Debug log:


Cheers!!!

August 16, 2012

Import using Apex in Salesforce

Visualforce page:


<apex:page controller="ImportCtrlr">
<apex:form >
<apex:pageblock >
<apex:pageBlockSection columns="2">
<apex:pageBlockSectionItem >
<apex:outputLabel value="Select Object"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:selectList size="1" value="{!obj}" >
<apex:selectOptions value="{!objs}"/>
</apex:selectList>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Select File"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:inputFile value="{!fileContent}" filename="{!fileName}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageblockButtons >
<apex:commandButton value="Import" action="{!importData}"/>
</apex:pageblockButtons>
</apex:pageblock>
</apex:form>
</apex:page>


Apex:

public class ImportCtrlr 
{
public Map<String, Schema.SObjectType> objs {get; set;}
public String obj {get;set;}
public Blob fileContent {get;set;}
public String filename {get;set;}
public List<List<String>> parsedCSVdata;
public List<sObject> sObjectDatatoStore;

public ImportCtrlr()
{
objs = Schema.getGlobalDescribe();
}

public void importData()
{
String fileString = fileContent.toString();
parsedCSVdata = parseCSV(fileString,false);
System.debug('Parsed CSV Data -->' + parsedCSVdata);
sObjectDatatoStore = csvTosObject(parsedCSVdata,obj);
System.debug('sObjectDatatoStore -->' + sObjectDatatoStore);
insert sObjectDatatoStore;
}

/* Method to parse CSV to List<List<String>> */
public List<List<String>> parseCSV(String contents,Boolean skipHeaders) 
{  

     List<List<String>> allFields = new List<List<String>>();  

     // replace instances where a double quote begins a field containing a comma  
     // in this case you get a double quote followed by a doubled double quote  
     // do this for beginning and end of a field  

     contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');  


     // now replace all remaining double quotes - we do this so that we can reconstruct  

     // fields with commas inside assuming they begin and end with a double quote  

     contents = contents.replaceAll('""','DBLQT');  


     // we are not attempting to handle fields with a newline inside of them  

     // so, split on newline to get the spreadsheet rows  

     List<String> lines = new List<String>();  


     try 

     {  
         lines = contents.split('\n');  
     } 
     catch (System.ListException e) 
     {  
         System.debug('Limits exceeded?' + e.getMessage());  
     }  

     Integer num = 0;  


     for(String line : lines)

{  

         // check for blank CSV lines (only commas)  


         if (line.replaceAll(',','').trim().length() == 0) break;             

         List<String> fields = line.split(',');      

         List<String> cleanFields = new List<String>();  


         String compositeField;  


         Boolean makeCompositeField = false;  


         for(String field : fields) 

         {  

             if (field.startsWith('"') && field.endsWith('"')) 

             {  
                 cleanFields.add(field.replaceAll('DBLQT','"'));  
             } else if (field.startsWith('"')) 
             {  
                 makeCompositeField = true;  
                 compositeField = field;  
             } 
             else if (field.endsWith('"')) 
             {  
                 compositeField += ',' + field;  
                 cleanFields.add(compositeField.replaceAll('DBLQT','"'));  
                 makeCompositeField = false;  

             } 

             else if (makeCompositeField) 
             {  
                 compositeField +=  ',' + field;  
             } 
             else 
             {  
                 cleanFields.add(field.replaceAll('DBLQT','"'));  
             }  
         }            
         allFields.add(cleanFields);  

     }  


     if (skipHeaders) allFields.remove(0);  


     return allFields;        
 

/* Method to parse List<List<String>> to sObject */
public list<sObject> csvTosObject(List<List<String>> parsedCSV, string objectType)
    {
        Schema.sObjectType objectDef = Schema.getGlobalDescribe().get(objectType).getDescribe().getSObjectType();
        System.debug('Object Definition --> ' + objectDef);
        
        list<sObject> objects = new list<sObject>();
        list<string> headers = new list<string>();
        
        for(list<string> row : parsedCSV)
        {
            for(string col : row)
            {
                headers.add(col);
            }
            break;
        }
        System.debug('Headers --> ' + headers);
        integer rowNumber = 0;
        for(list<string> row : parsedCSV)
        {
            if(rowNumber == 0)
            {
                rowNumber++;
                continue;
            }
            else
            {
                sObject thisObj = objectDef.newSobject();
                integer colIndex = 0;
                for(string col : row)
                {                   
                    string headerName = headers[colIndex].trim();
                    system.debug('========================= Column Name ' + headerName);
                    if(headerName.length() > 0)
                    {                  
                        try
                        {                       
                        if(col.contains('/'))
                        {
                        Date tempDate;
                        String[] tempStr = col.split('/');
                        Integer d = Integer.valueOf(tempStr[0]);
                        Integer m = Integer.valueOf(tempStr[1]);
                        Integer y = Integer.valueOf(tempStr[2]);
                        tempDate = Date.newInstance(y,m,d);
                        thisObj.put(headerName,tempDate);
                        }
                        else
                        {
                        thisObj.put(headerName,col.trim());
                        }                            
                        }
                        catch(exception e)
                        {
                            system.debug('============== Invalid field specified in header ' + headerName);                           
                        }
                        colIndex++;
                    }
                } 
                objects.add(thisObj);
                rowNumber++;
            }       
        }        
        System.debug('Object Data --> ' + objects);
        return objects;
    }
}

Cheers!!!

August 14, 2012

How to truncate string using apex in Salesforce?

To truncate string using apex in Salesforce

String str = 'sfdcblog';
String trucatedStr = str.substring(0,3);


Cheers!!!

Parsing CSV to sObject using Apex in Salesforce

To parse CSV to sObject using Apex in Salesforce, use the below link to get the code

http://wiki.developerforce.com/page/Code_Samples#Parse_a_CSV_with_APEX

Sample code:

  1. public List<List<String>> parseCSV(String contents,Boolean skipHeaders) {    
  2.   
  3.      List<List<String>> allFields = new List<List<String>>();      
  4.      // replace instances where a double quote begins a field containing a comma  
  5.      // in this case you get a double quote followed by a doubled double quote    
  6.      // do this for beginning and end of a field    
  7.  
  8.      contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');    
  9.   
  10.      // now replace all remaining double quotes - we do this so that we can reconstruct 
  11.      // fields with commas inside assuming they begin and end with a double quote     
  12.   
  13.      contents = contents.replaceAll('""','DBLQT');    
  14.  
  15.      // we are not attempting to handle fields with a newline inside of them  
  16.      // so, split on newline to get the spreadsheet rows     
  17.   
  18.      List<String> lines = new List<String>();      
  19.   
  20.      try {    
  21.   
  22.          lines = contents.split('\n');    
  23.   
  24.      }  catch (System.ListException e) {    
  25.   
  26.          System.debug('Limits exceeded?' + e.getMessage());    
  27.   
  28.      }     
  29.   
  30.      Integer num = 0;      
  31.   
  32.      for(String line : lines) {    
  33.   
  34.          // check for blank CSV lines (only commas)      
  35.   
  36.          if (line.replaceAll(',','').trim().length() == 0) break;               
  37.   
  38.          List<String> fields = line.split(',');          
  39.          List<String> cleanFields = new List<String>();    
  40.          String compositeField;  
  41.          Boolean makeCompositeField = false;    
  42.   
  43.   
  44.          for ( String field : fields ) {    
  45.   
  46.              if (field.startsWith('"') && field.endsWith('"')) {    
  47.   
  48.                  cleanFields.add(field.replaceAll('DBLQT','"'));    
  49.   
  50.              } else if (field.startsWith('"')) {    
  51.   
  52.                  makeCompositeField = true;  
  53.                  compositeField = field;    
  54.   
  55.              } else if (field.endsWith('"')) {    
  56.   
  57.                  compositeField += ',' + field;    
  58.                  cleanFields.add(compositeField.replaceAll('DBLQT','"'));    
  59.                  makeCompositeField = false;    
  60.   
  61.   
  62.              } else if (makeCompositeField) {    
  63.   
  64.                  compositeField +=  ',' + field;    
  65.   
  66.              } else {    
  67.   
  68.                  cleanFields.add(field.replaceAll('DBLQT','"'));    
  69.   
  70.              }    
  71.   
  72.          }              
  73.   
  74.          allFields.add(cleanFields);    
  75.   
  76.      }    
  77.   
  78.      if (skipHeaders) allFields.remove(0);      
  79.   
  80.      return allFields;          
  81.   
  82. }   

Here contents is fileContent.toString(). Where fileContent is the value of file mentioned in <apex:inputFile.>

Example:

<apex:inputFile value = "{!fileContent}" name = "{!fileName}"/>