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!!!

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!!!

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 previous action.

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
Cheers!!!

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!!!

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!!!

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);
}
}

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!!!

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!!!

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!!!

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

Cheers !!!

Sample code:

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;         





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

Example:

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

Cheers!!!

Import Wizard in Salesforce

The import wizard imports Accounts, Contacts, Leads, Solutions and Custom Object data.

The inbuilt Import wizard's advantages:
  • You need not install any third party tool
  • Your data is small and is in CSV format
You can access the inbuilt import wizard through Setup --> Administration Setup --> Data Management. This wizard only supports a maximum of 50,000 records per import.



Note:
  • Instead of  false or true value for checkbox, you should use 0 or 1.
  • Date/Time format will follow your personal locale setting. In most situations, the format should be MM/DD/YYYY.
  • If the field length is exceeded, the import wizard will truncate the data.
Cheers!!!

How to get list of objects used in an organization using apex in Salesforce?

Sample code:
//Just to display, use the below code. public class ImportCtrlr 
{
    public Map<String, Schema.SObjectType> objs {get; set;}

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

For manipulation with list of objects:

Visualforce page:

    <apex:page controller="objectList" >     
    <apex:form >
        <apex:SelectList value="{!name}" size="1">
            <apex:selectOptions value="{!names}"></apex:selectOptions>
        </apex:SelectList>
    </apex:form>
    </apex:page>



Apex Controller:

    public class objectList
    {
      public String name {get;set;}
     
      public List<SelectOption> getNames()
      {
          List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();   
          List<SelectOption> options = new List<SelectOption>();
        
          for(Schema.SObjectType f : gd)
          {
             options.add(new SelectOption(f.getDescribe().getName(),f.getDescribe().getName()));
          }
          return options;
       }
    }


Cheers!!!

Slide Show in Salesforce

Visualforce:

<apex:page standardController="Photo__c" extensions="SlideShow" sidebar="false">

  <apex:form >

    <center>

    <apex:image url="{!tmp}"/>

    <br/>
    <br/>
    <br/>
   
    <apex:commandButton action="{!prev}" value="Previous"/>&nbsp;&nbsp;&nbsp;
    <apex:commandButton action="{!nxt}" value="Next"/>

    </center>

  </apex:form>

</apex:page>


Apex Controller:

Public Class SlideShow
{
    public List<Photo__c> photo {get; set;}
    public String imageTag {get; set;}
    public String photoUrl {get; set;}
    public Integer strt=0,ed=1,len=0,i=0,indx=0;
   
    public String tmp {get; set;}
   
    public SlideShow(ApexPages.StandardController controller)
    {          
      String sql = 'SELECT image__c FROM Photo__c';
      photo = Database.query(sql);
      imageTag = photo.get(indx).image__c;
     
      strt = imageTag.indexOf('src=',0) + 5;
      ed = imageTag.lastIndexOf('alt=') - 2;
      tmp = imageTag.substring(strt,ed);
    }          
   
    public void prev()
    {
      if(indx != 0)
      {
      indx = indx - 1;
      String sql = 'SELECT image__c FROM Photo__c';
      photo = Database.query(sql);
      imageTag = photo.get(indx).image__c;
     
      strt = imageTag.indexOf('src=',0) + 5;
      ed = imageTag.lastIndexOf('alt=') - 2;
      tmp = imageTag.substring(strt,ed);
      }
    }   

    public void nxt()
    {  
      len = [SELECT COUNT() FROM Photo__c];
      if(indx != (len-1))
      {
      indx = indx + 1;
      String sql = 'SELECT image__c FROM Photo__c';
      photo = Database.query(sql);
      imageTag = photo.get(indx).image__c;
     
      len =imageTag.length();
      strt = imageTag.indexOf('src=',0) + 5;
      ed = imageTag.lastIndexOf('alt=') - 2;
      tmp = imageTag.substring(strt,ed);
      }     
    }       
}

Cheers!!!