Fetching data from another Salesforce organization

Fetching data from another Salesforce organization

Step 1: Generate
Partner WSDL.

Save
the generated Partner WSDL.
Step 2: Generate Apex code using the
generated Partner WSDL.

 

Copy the generated code and create a new Apex Class.
Note:
In the generated code do the following changes.
  1. Change
    public partnerSoapSforceCom.DeleteResult[]
    delete(String[] ids)
      to public partnerSoapSforceCom.DeleteResult[]
    deleteSObjects(String[] ids)
    .
  2. Change
    public partnerSoapSforceCom.UpsertResult[]
    upsert(String externalIDFieldName,sobjectPartnerSoapSforceCom.sObject_x[]
    sObjects)
    to public
    partnerSoapSforceCom.UpsertResult[] upsertSObjects(String
    externalIDFieldName,sobjectPartnerSoapSforceCom.sObject_x[] sObjects)
    .
  3. Change public
    partnerSoapSforceCom.MergeResult[]
    merge(partnerSoapSforceCom.MergeRequest[] request)
    to public
    partnerSoapSforceCom.MergeResult[] mergeSObjects
    (partnerSoapSforceCom.MergeRequest[] request).
  4. Change public
    partnerSoapSforceCom.SaveResult[] update(sobjectPartnerSoapSforceCom.sObject_x[]
    sObjects)
    to public partnerSoapSforceCom.SaveResult[] updateSObjects(sobjectPartnerSoapSforceCom.sObject_x[]
    sObjects).
  5. Change public
    partnerSoapSforceCom.UndeleteResult[] undelete(String[] ids)
    to public partnerSoapSforceCom.UndeleteResult[]
    undeleteSObjects(String[] ids).

Step 3:  Create visual force page to get the following
details

  • Login
    credentials
  • Object
    Names
  • Field
    Names
  • Records

Sample Code:
<apex:page controller=”sfTosf” >
<!– Javascript –>
<script type = “text/javascript”>
   
window.onload=function()      
    {         
       
document.getElementById(“objs”).style.display = ‘none’;
       
document.getElementById(“fields”).style.display = ‘none’;
       
document.getElementById(“records”).style.display = ‘none’;
    };
   
    function
callObjects()
    {
       
document.getElementById(“objs”).style.display = ”;
        CallLogin();
    }
    function
callFields()
    {
       
document.getElementById(“fields”).style.display = ”;
       
CallShowFields();
    }
   
    function
callRecords()
    {
       
document.getElementById(“records”).style.display = ”;
       
CallShowRecords();
    }
   
</script>
<!– End of Javascript –>
<apex:form >
    <!– Action
Status –>
    <apex:actionstatus
id=”actionStatus”>
    <apex:facet
name=”start”>
   
<c:enhancedactionstatus BackColor=”#efefef”
borderColor=”black” borderSize=”3″ height=”50px”
width=”120px” Message=”Loading…” messageStyle=”color:darkred;font-size:11pt;font-weight:bold;”/>
   
</apex:facet>
   
</apex:actionStatus>
   
    <!– Calling
login() from Controller –>
   
<apex:actionFunction name=”CallLogin”
action=”{!login}” reRender=”objs”
status=”actionStatus”/>   
    <!– Calling
showFields() from Controller –>
   
<apex:actionFunction name=”CallShowFields”
action=”{!showFields}” reRender=”fields”
status=”actionStatus”/>
   
    <!– Calling
fetch() from Controller –>
   
<apex:actionFunction name=”CallShowRecords”
action=”{!fetch}” reRender=”records” status=”actionStatus”/>    
    <!– Login
Details –>
    <apex:pageblock
title=”Login” >
       
<apex:pageblocksection columns=”2″>
           
<apex:outputLabel >Username:</apex:outputLabel>
           
<apex:inputtext value=”{!userName}” />
            <apex:outputLabel
>Password:</apex:outputLabel>
           
<apex:inputsecret value=”{!passWord}”  />          
           
<apex:outputLabel >Security Token:</apex:outputLabel>                       
           
<apex:inputsecret value=”{!securityToken}”  />             
       
</apex:pageblocksection>                      
       
<apex:pageblockbuttons >
           
<apex:commandButton value=”Login” reRender=”objs”
onclick=”callObjects()”/>
       
</apex:pageblockbuttons>           
    </apex:pageblock>
   
    <!– Object
Details –>
    <table id =
“objs” width = “100%”><tr><td>
    <apex:pageblock
id=”objs” title=”Object Selection”>
       
<apex:pageblocksection >
           
<apex:outputlabel >Select Object:</apex:outputlabel>
            <apex:selectList
value=”{!objectName}” multiselect=”false”
size=”1″ onchange=”callFields()” >
               
<apex:selectoptions value=”{!ObjectNames}”/>
           
</apex:selectList>
       
</apex:pageblocksection>
   
</apex:pageblock>
   
</td></tr></table>
   
    <!– Fields
Details –>
    <table id =
“fields” width = “100%”><tr><td>
    <apex:pageblock
id=”fields” title=”Fields Selection”>
        <table
cellspacing = “15”>
            <tr>
               
<td>
                   
<apex:selectList multiselect=”true”
value=”{!selectedFields}” size=”7″ >
                       
<apex:selectoptions value=”{!fields}”/>
                   
</apex:selectList>
               
</td>
               
<td>
                   
<apex:commandButton value=” >> ” action =
“{!addFields}” reRender = “fields”
status=”actionStatus”/><br/><br/><br/><br/>
                   
<apex:commandButton value=” << ”
action=”{!removeFields}” reRender=”fields”
status=”actionStatus”/>  
               
</td>
               
<td>
                    <apex:selectList
multiselect=”true” value=”{!checkedFields}”
size=”7″>
                       
<apex:selectoptions value=”{!fieldsAvailable}”/>
                   
</apex:selectList>
               
</td>               
           
</tr>
            <tr>
                <td
colspan = “3” align = “center”><apex:commandButton
value=”Fetch” rerender=”records”
onclick=”callRecords()”/></td>
           
</tr>
        </table>
   
</apex:pageblock>
   
</td></tr></table>
   
    <!– Retrieved
Records –>   
    <table id =
“records” width = “100%”><tr><td>
    <apex:pageBlock
id=”records” title=”Records”>
       
<apex:pageBlockTable value=”{!output}”
var=”res”>
           
<apex:column value=”{!res}”/>
       
</apex:pageBlockTable>
    </apex:pageBlock>
   
</td></tr></table>  
     
</apex:form>
</apex:page>
Step 4:  Write an apex class for controller to that
visualforce page.
Sample Code:
public class sfTosf
{
    public String
userName {get;set;}   
    public String
passWord {get;set;}
    public String
securityToken {get;set;}  
    public String
objectName {get;set;}
    public String[]
objNames = new String[]{‘None’};
    public
List<String> fieldNames = new List<String>();
    public
List<String> availableFieldNames = new List<String>();
    public
sobjectPartnerSoapSforceCom.sObject_x[] values;  
    public
List<String> output {get; set;}
    public integer i
{get;set;}
    public integer j =
0;
       
    /* String array
for select box(Fields) */
    String[]
selectedFields = new String[]{};
    String[]
checkedFields = new String[]{};
   
    public
partnerSoapSforceCom.Soap con = new partnerSoapSforceCom.Soap();
   
    public void
login()
    {
       
if(checkLogin())
        {
           
retrieveObjects();
        }
    }
   
    public boolean
checkLogin()
    {
        try
        {                                 
           
partnerSoapSforceCom.LoginResult loginResult = con.login(username,
(password+securityToken));                   
           
con.SessionHeader = new
partnerSoapSforceCom.SessionHeader_element();       
           
con.endpoint_x =loginResult.ServerUrl;       
           
con.Sessionheader.sessionid = loginResult.sessionid;
        }
       
catch(Exception e)
        {
        }
        return true;
     }
    
     /* Retrieving all
the objects */
     public void
retrieveObjects()
     {
        
if(checkLogin())
         {
            
partnerSoapSforceCom.DescribeGlobalresult sobjectResults =
con.describeGlobal();
             partnerSoapSforceCom.DescribeGlobalSObjectResult[]
objects = sobjectResults.sobjects;        
            
for(partnerSoapSforceCom.DescribeGlobalSObjectResult tmpRes:objects)
             {
                
objNames.add(tmpRes.Name);
             }
         }
     }
    
     /* Getting the
selected object name */
     public String
getobjectName()    
     {     
         return
objectName;   
     }       
     public void
setobjectName(String obj)    
     {     
        
this.objectName = objectName;    
     }
     
     public
List<SelectOption> getobjectNames()   
     {         
        
List<SelectOption> options = new List<SelectOption>();
         for(String
temp:objNames)
         {    
        
options.add(new SelectOption(temp,temp));
         }     
         return
options;   
     }
    
     public void
showFields()
     {
        
if(checkLogin())
         {
            
partnerSoapSforceCom.DescribeSObjectResult descObjRes =
con.describeSObject(objectName);
            
partnerSoapSforceCom.Field[] fields = descObjRes.Fields;
            
for(partnerSoapSforceCom.Field tmpRes:fields)
             {
                
fieldNames.add(tmpRes.Name);               
             }                    
         }        
     }
    
     /* Getting the
all the field names */
     public
List<String> getselectedFields()    
     {     
         return
selectedFields;   
     }       
     public void
setselectedFields(List<String> selectedFields)    
     {     
         this.selectedFields
= selectedFields;   
     }
          
     public
List<SelectOption> getfields()   
     {         
        
List<SelectOption> options = new List<SelectOption>();
        
fieldNames.sort();
         for(String
temp:fieldNames)
         {    
        
options.add(new SelectOption(temp,temp));
         }     
         return
options;   
     }
    
     /* Getting the
all the field names */
     public
List<String> getcheckedFields()    
     {     
         return
checkedFields;   
     }       
     public void
setcheckedFields(List<String> checkedFields)    
     {     
        
this.checkedFields = checkedFields;   
     }
          
     public
List<SelectOption> getfieldsAvailable()   
     {         
        
availableFieldNames.sort();
        
List<SelectOption> options = new List<SelectOption>();
         for(String
temp:availableFieldNames)
         {    
            
options.add(new SelectOption(temp,temp));
         }     
         return
options;   
     }
    
     public void addFields()
     {
         for(String
tmp:selectedFields)
         {
            
availableFieldNames.add(tmp);
             for(i =
0; i<fieldNames.size(); i++)
             {
                
if(fieldNames[i] == tmp)
                 {
                     fieldNames.remove(i);
                    
break;
                 }
             }                         
         }
     }   
    
     public void
removeFields()
     {
         integer i;
         for(String
tmp:checkedFields)
         {
            
fieldNames.add(tmp);
             for(i =
0; i<availableFieldNames.size(); i++)
             {
                
if(availableFieldNames[i] == tmp)
                 {
                    
availableFieldNames.remove(i);
                     break;
                 }
             }                         
         }
     }
     public void
fetch()
     {
        
if(checkLogin())
         {
             integer
availableFieldNamesLen = availableFieldNames.size();
             String
fieldsToQuery = ”;
            
for(String temp:availableFieldNames)
             {
                 if(j
!= (availableFieldNameslen – 1))
                 {
                    
fieldsToQuery = fieldsToQuery + temp + ‘,’;
                 }
                 else
                 {
                    
fieldsToQuery = fieldsToQuery + temp;
                
}                
                 j = j
+1;
             }
             String
sql = ‘SELECT ‘ + fieldsToQuery + ‘ FROM ‘ + objectName;              
                
        
            
/*———————————–
             Login via
SOAP/XML web service api
           
———————————–*/
           
HttpRequest request = new HttpRequest();
           
request.setEndpoint(‘https://www.salesforce.com/services/Soap/u/22.0’);
           
request.setMethod(‘POST’);
           
request.setHeader(‘Content-Type’, ‘text/xml;charset=UTF-8’);
           
request.setHeader(‘SOAPAction’, ‘””‘);
            /*not
escaping username and password because we’re setting those variables above
            in other
words, this line “trusts” the lines above
            if
username and password were sourced elsewhere, they’d need to be escaped below*/
           
request.setBody(‘<Envelope xmlns=”http://schemas.xmlsoap.org/soap/envelope/”><Header/><Body><login
xmlns=”urn:partner.soap.sforce.com”><username>’ + userName+
‘</username><password>’ + passWord + securityToken + ‘</password></login></Body></Envelope>’);
           
Dom.XmlNode resultElmt = (new
Http()).send(request).getBodyDocument().getRootElement()
             
.getChildElement(‘Body’, ‘http://schemas.xmlsoap.org/soap/envelope/’)
             
.getChildElement(‘loginResponse’, ‘urn:partner.soap.sforce.com’)
             
.getChildElement(‘result’, ‘urn:partner.soap.sforce.com’);
   
           
/*——————————-
             Grab
session id and server url
           
——————————–*/
            final
String SERVER_URL = resultElmt.getChildElement(‘serverUrl’,
‘urn:partner.soap.sforce.com’) .getText().split(‘/services’)[0];
            final
String SESSION_ID = resultElmt.getChildElement(‘sessionId’,
‘urn:partner.soap.sforce.com’) .getText();
   
           
/*———————————-
             Load first 20 accounts via REST API
           
———————————*/
            final
PageReference theUrl = new PageReference(SERVER_URL +
‘/services/data/v22.0/query/’);
           
theUrl.getParameters().put(‘q’,sql);
            request =
new HttpRequest();
           
request.setEndpoint(theUrl.getUrl());
           
request.setMethod(‘GET’);
           
request.setHeader(‘Authorization’, ‘OAuth ‘ + SESSION_ID);
   
            String
body = (new Http()).send(request).getBody();
   
            JSONParser
parser = JSON.createParser(body);
   
            do
            {
               
parser.nextToken();
            }
           
while(parser.hasCurrentToken() &&
!’records’.equals(parser.getCurrentName()));
   
            parser.nextToken();
   
           
List<String> tmpOutput = (List<String>)
parser.readValueAs(List<String>.class); 
            //output =
tmpOutput;                   
           
List<String> tempoutput = new List<String>();
            for(String
tmp:tmpOutput)
            {
                if(tmp
!= null)
                {
                   
if(!tmp.contains(‘attributes’) && !tmp.contains(‘type’)
&& !tmp.startsWith(‘/services/data/v22.0’) &&
!tmp.contains(‘url’) && tmp != objectName && !tmp.contains(‘{‘)
&& !tmp.contains(‘}’))
                    {
                       
tempoutput.add(tmp);
                    }
                }
            }
            output =
tempoutput;
        } 
     } 
}
Step 5:  Create a custom component for action status
with name “enhancedactionstatus”.

To create custom component, Setup à Develop à Components

enhancedactionstatus custom component
Sample Code:
<apex:component >
<!-- Attribute Definitions -->
<apex:attribute name="BorderColor" type="String" required="true" description=""></apex:attribute>
<apex:attribute name="Width" type="String" required="true" description=""></apex:attribute>
<apex:attribute name="Height" type="String" required="true" description=""></apex:attribute>
<apex:attribute name="BackColor" type="String" required="true" description=""></apex:attribute>
<apex:attribute name="BackColor" type="String" required="true" description=""></apex:attribute>
<apex:attribute name="BorderSize" type="String" required="true" description=""></apex:attribute>
<apex:attribute name="ImageUrl" type="String" required="false" description=""></apex:attribute>
<apex:attribute name="Message" type="String" required="false" description=""></apex:attribute>
<apex:attribute name="messageStyle" type="String" required="false" description="Message inline style">
</apex:attribute>
<apex:attribute name="BorderStyle" type="String" 
required="false" description="Message box border style: solid, outset, inset, etc"></apex:attribute>
 
<div id="salesforceSource_blurybackground" style="position:absolute; left:1px; top:1px; 
width:100%; height:100%; text-align:center; vertical-align: 
middle; background-color: #303030; opacity:0.6; filter:alpha(opacity=50)">
</div>
 
<div id="salesFroceSource_StatusBox" 
style="position:absolute; left:100px; top: 100px;width: {!Width}; height:{!Height}; filter:alpha(opacity=100)">
<table border="{!BorderSize}" cellpadding="0" cellspacing="0" style="border-left-color: {!BorderColor};
border-bottom-color: {!BorderColor}; width: {!Width}; border-top-color: {!BorderColor}; height:{!Height};
border-right-color:{!BorderColor}; border-style:{!BorderStyle}; background-color:{!BackColor};">
<tr>
<td align = "center" style="border-bottom-color:{!BorderColor}; border-bottom-width:1px; 
border-bottom-style:solid;vertical-align:middle;{!messageStyle}">
&nbsp;{!Message}
</td>
</tr>
</table>
</div>
 
<script type="text/javascript">
var AgreementForm = document.getElementById("salesforceSource_blurybackground");
AgreementForm.style.height = window.screen.availHeight + "px";
AgreementForm.style.width = window.screen.availWidth + "px";
 
var ContainerElem = document.getElementById("salesFroceSource_StatusBox");
//ContainerElem.style.display = "block";
AlignToCenter(ContainerElem);
 
function AlignToCenter(Element)
{
var availableHeight = 0;
var availableWidth = 0;
if (Element.ownerDocument)
{
var docElement = Element.ownerDocument.documentElement;
availableHeight = parseInt(docElement.clientHeight);
if (availableHeight == "NaN") availableHeight = 0;
 
availableWidth = parseInt(docElement.clientWidth);
if (availableWidth == "NaN") availableWidth = 0;
}
 
if (availableHeight == 0 || availableHeight == "NaN")
availableHeight = window.screen.availHeight - 200;
if (availableWidth == 0 || availableWidth == "NaN")
availableWidth = window.screen.availWidth - 100;
 
var msgBoxTop = parseInt((availableHeight - parseInt(Element.clientHeight))/2);
var msgBoxleft = parseInt((availableWidth - parseInt(Element.style.width))/2);
 
if (msgBoxTop == "NaN" || msgBoxTop == 0)
msgBoxTop = 100;
 
Element.style.left = msgBoxleft + "px";
Element.style.top = msgBoxTop + "px";
}
</script>
</apex:component>

Output:

Leave a Reply