Sunday, August 13, 2017

Dynamic Search Engine Advanced

===============================================================
This topic covers, Dynamic query, apex:actionfunction, column level sorting,Html tables tr and td's,apex:param, rerendering,pageblock's inside the pageblocks and also page error messages.

Note: To execute below code you need to create picklist value custom field in contacts with the API name:"Intrested_technologies_to_learn__c"

==================================================================

Vf page:
---------

<apex:page controller="ContactSearchController" sidebar="false" >

  <apex:form >
  <apex:pageMessages id="errors" />

  <apex:pageBlock title="Find Me A Customer!" mode="edit">

  <table width="100%" border="0">
  <tr>
    <td width="200" valign="top">

      <apex:pageBlock title="Parameters" mode="edit" id="criteria">

      <script type="text/javascript">
     
      function doSearch() {
        searchServer(
          document.getElementById("firstName").value,
          document.getElementById("lastName").value,
          document.getElementById("accountName").value,
          document.getElementById("technology").options[document.getElementById("technology").selectedIndex].value
          );
      }
      </script>

      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="firstName" value="" />
          <apex:param name="lastName" value="" />
          <apex:param name="accountName" value="" />
          <apex:param name="technology" value="" />
      </apex:actionFunction>

      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">First Name<br/>
       
        <input type="text" id="firstName" onkeyup="doSearch();"/>
       
        </td>
      </tr>
     
      <tr>
        <td style="font-weight:bold;">Last Name<br/>
        <input type="text" id="lastName" onkeyup="doSearch();"/>
        </td>
      </tr>
     
      <tr>
        <td style="font-weight:bold;">Account<br/>
        <input type="text" id="accountName" onkeyup="doSearch();"/>
        </td>
      </tr>
     
      <tr>
        <td style="font-weight:bold;">Interested Technologies<br/>
          <select id="technology" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!technologies}" var="tech">
              <option value="{!tech}">{!tech}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
     
      </table>

      </apex:pageBlock>

    </td>

    <td valign="top">

    <apex:pageBlock mode="edit" id="results">

        <apex:pageBlockTable value="{!contacts}" var="contact">

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="First Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="firstName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.firstName}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Last Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="lastName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.lastName}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Account" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.name}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Technologies" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Intrested_technologies_to_learn__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.Intrested_technologies_to_learn__c}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageBlock>

    </td>
  </tr>
  </table>

  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />          
  </apex:pageBlock>  

  </apex:pageBlock>

  </apex:form>
</apex:page>


======================================================================

Controller code:
-----------------

public with sharing class ContactSearchController {

  // the soql without the order and limit
 
  private String soql {get;set;}
 
 
  // the collection of contacts to display
  public List<Contact> contacts {get;set;}

  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'lastName'; } return sortField;  }
    set;
  }

  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public ContactSearchController() {
    soql = 'select firstname, lastname, account.name, Intrested_technologies_to_learn__c from contact where account.name != null';
    runQuery();
  }

  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      contacts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
   
    system.debug('$$$$$$$$$$$$$$$$$$$'+e);
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {

    String firstName = Apexpages.currentPage().getParameters().get('firstname');
   
    String lastName = Apexpages.currentPage().getParameters().get('lastname');
   
    String accountName = Apexpages.currentPage().getParameters().get('accountName');
   
    String technology = Apexpages.currentPage().getParameters().get('technology');
   
    system.debug('$$$$$$$$$$$$$$$$$$$$$$'+technology);

    soql = 'select firstname, lastname, account.name, Intrested_technologies_to_learn__c from contact where account.name != null';
   
if (!firstName.equals(''))
      soql += ' and firstname LIKE \''+String.escapeSingleQuotes(firstName)+'%'+'\'';
    if (!lastName.equals(''))
      soql += ' and lastname LIKE \''+String.escapeSingleQuotes(lastName)+'%'+'\'';
    if (!accountName.equals(''))
      soql += ' and account.name LIKE \''+String.escapeSingleQuotes(accountName)+'%'+'\'';
    if (!technology.equals(''))
      soql += ' and Intrested_technologies_to_learn__c = \'' +String.escapeSingleQuotes(technology)+'\'';
 system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'+soql);

 //' LastName like \''+LastName+'\'';
           // }
    // run the query again
    runQuery();

    return null;
  }

  // use apex describe to build the picklist values
  public List<String> technologies {
    get {
      if (technologies == null) {

        technologies = new List<String>();
        Schema.DescribeFieldResult field = Contact.Intrested_technologies_to_learn__c.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          technologies.add(f.getLabel());

      }
      return technologies;        
    }
    set;
  }

}

Sunday, July 30, 2017

Salesforce Certified Platform App Builder – Summer ’17 Release Exam


1 of 5.
How can users see the change history of key fields in an object record?
A. History related list with field tracking
B. Reporting Snapshot
C. Historical Trend Reporting
D. Setup Audit Trail

2 of 5.
Which two components are supported when building Lightning pages with the Lighting App Builder?
Choose 2 answers

A. Related Records
B. Chatter Feed
C. Social View
D. Flows

3 of 5.
What is a secure method of creating a single field from two encrypted fields?
A. Create the two source fields, use a formula with & to concatenate, populate the data into the two source fields, then encrypt the source fields
B. Create a custom formula referencing the two encrypted fields using & to concatenate
C. Disable encryption on the two source fields, create a formula using & to concatenate, then reenable encryption on the two source fields
D. Disable Shield Platform Encryption, create a formula using & to concatenate, then reenable Shield Platform Encryption


4 of 5.
What happens to an automated notification email generated by a process if another process subsequently modifies the same record?
A. The email is sent twice.
B. The email is suppressed.
C. The email is queued and may send depending on the secondary process.
D. The email is sent.
5 of 5.
Which tool will help the consultant see if APEX or Visualforce code is running an out-of-date API version?

A. Optimizer
B. Lightning Experience Readiness Check
C. Lightning Experience Migration Assistant
D. Health Check

Salesforce Certified Platform Developer I – Summer ’17 Release Exam

Salesforce Certified Platform Developer I – Summer ’17 Release Exam


1 of 5.
What are two considerations when overriding standard actions?
Choose 2 answers
A. Overriding standard actions with a Lightning component applies only to Lightning Experience and Salesforce1, but not to Salesforce Classic.
B. Overriding standard actions with a Visualforce page applies only to Salesforce Classic and Lightning Experience, but not to Salesforce1.
C. Overriding standard actions with a Visualforce page applies to Salesforce Classic, Lightning Experience, and Salesforce1.
D. Overriding standard actions with a Lightning component applies to Lightning Experience, Salesforce1, and Salesforce Classic.


2 of 5.
How can a validity check be performed on a component?A
A. cmp.get() != null
B. cmp.get() == true
C. cmp.get(“v.isValid”) != null
D. cmp.get(“v.isValid”) == true


3 of 5.
Which standard actions can be overridden with Lightning Components?
A. Tab, View, Edit, New
B. View, Edit, New, Delete
C. List, Edit, New, Delete
D. List, View, Edit, New


4 of 5.
What is a consideration for Locker Service Enablement?
A. Locker service is enabled for all custom Lightning Components with API version 40.0 or greater.
B. Locker service is disabled for all custom Lightning Components, regardless of the API version.
C. Locker service is disabled for custom Lightning Components implementing the interface force:ignoreLockerService.
D. Locker service is enabled for custom Lightning Components implementing the interface force:enforceLockerService.


5 of 5.
How do the CSS enhancements to the Lightning Design System improve the developer experience? A
A. Single dashes are used in class names to enable commenting.
B. Uppercase is used to distinguish from custom class names.
C. Class names are available in upper and lower case.
D. Class names are abbreviated to reduce code length.

Summer ’17 Release Administrator maintenance Exam


1 of 5.
what action can be taken in Lightning, if you receive an approval request that someone
else should approve?
A. Delete the associated record.
B. Change approval Entry Criteria.
C. Edit Approval Process Manager
D. Re-assign the approval request
2 of 5.
How can an administrator allow users to choose different views of a dashboard in Lightning Experience?D
A. Dashboard designer
B. Report filters
C. Report creator
D. Dashboard filters
3 of 5.
Which two chatter groups will show a seen by count of people who viewes the post, in the Lightning Experience? choose 2 answers CD
A. Public
B. Restricted
C. Unlisted
D. Private
4 of 5.
where are the files and related records attached when a sales user converts a lead? C
A. Contact, account, person account, Opportunity records.
B. Contact, account, opportunity, quote records.
C. Contact, account, opportunityrecords
D. Contact account, person account records
5 of 5.
which two feature best describe the new Lightning optimized Log a call action? choose 2 answers BC
A. Autopopulate the case team
B. Autopopulate the case contact
C. Autolink the call log to the case
D. Autolink the audit log to the case

Integrate with Active Campaign

>>To integrate with Active campaign first register with free trail edition by the below link

http://www.activecampaign.com/free/


>> After logging in create a list by clicking on LIST TAB


>>At the complete right top of the screen,click on your profile and click on my settings.

>>under your settings take the key and url and use them in the following code.

Ex: Key='a1228bae475b1f07c64dbf7d4018758c5f3cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

      url='https://sfdc550.activehosted.com;

>> please register Active campaign url in the salesforce remote site settings.

EX: https://tcs550.activehosted.com


Step 1:

create below class in the Salesforce org, this is to control recursion

public class recursioncontrol {     public static boolean firstRun = true;  }
   
Step 2:
create below class in the Salesforce org, this contains http code.

public class activecamp { @future (callout=true) public static void contactcreation(string firstname, string lastname, string email) { String APIkey='a1228bae475b1f07c64dbf7d4018758c5f3cac6b036c4c0c1afa70e5051c1cd5dcbd099b'; String apiaction='contact_add'; string hostname='https://tcs550.api-us1.com/admin/api.php?'; string apioutput='json'; String thirdpartyendpoint=hostname+'api_key='+APIkey+'&api_action='+apiaction+'&api_output='+apioutput;  HttpRequest req=new HttpRequest();     req.setMethod('POST');          req.setEndpoint(thirdpartyendpoint);              req.setBody('Content-Type=application/x-www-form-urlencoded');               string targetString='email='+email +'&first_name='+firstname+'&last_name='+lastname+'&p[1]=1';     req.setBody('Content-Length="512"');  req.setBody(targetString);     System.debug('HttpRequest :' +req); System.debug('HttpRequest :' +req.getBody());  HttpResponse response = null;     Http http = new Http();     response = http.send(req); system.debug('@@@@@@@@@@@'+response);     system.debug('@@@@@@@@@@@'+response.getBody()); } }

Step 3:

Copy this code in the contact triggers, this helps to integrate in real time
trigger syncwithactivecampaigns on Contact (after insert, after update) {



For(Contact c1:Trigger.new){

if(recursioncontrol.firstrun){

//activecampint.contactupdatecreation(c1.firstname,c1.lastname,c1.email,integer.valueof(c1.phone));

activecamp.contactcreation(c1.firstname,c1.lastname,c1.email);

recursioncontrol.firstrun=false;
}

}


}

Friday, July 28, 2017

Salesforce to Salesforce Inbound/outbound integration

Paste this code in the target org

============================
@RestResource(urlMapping='/v1/CustomResturl/*')

   global with sharing class getContact {
   
     @Httpget
      global static list<contact> mycontacts(){
        RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
      
        list<contact> lstcontact =[Select id , name,Email from contact];
        
        system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'+lstcontact);
        
        return lstcontact ;
      }
      
     
   }
==================================

Execute below code in the Source org
==========================



public class DeserializeJsonResp
   {
      public String id;
      public String access_token;
   }

String reqbody = 'grant_type=password&client_id='+'your clientid which you got from your third party connected app'+'&client_secret='+'your secret key which you got from your third party connected app'+'&username='+'jagadeesh777@chitti.com'+'&password='+'yourpasswordsecuritytoken';

System.debug('%%%%%%%%%%%%%%%%%'+reqbody);

Http h = new Http();
      HttpRequest req = new HttpRequest();

      req.setBody(reqbody);

      req.setMethod('POST');

      req.setEndpoint('https://jagadeesh777-dev-ed.my.salesforce.com/services/oauth2/token');

      HttpResponse res = h.send(req);

System.debug('&&&&&&&&&&&&&&&&'+res.getbody());

 DeserializeJsonResp responsewithtoken = (DeserializeJsonResp)JSON.deserialize(res.getbody(),DeserializeJsonResp.class);
     system.debug('@@@@access_token@@'+responsewithtoken );



           Http h2 = new Http();
           HttpRequest req1 = new HttpRequest();
           req1.setHeader('Authorization','Bearer ' + responsewithtoken.access_token);
           req1.setHeader('Content-Type','application/json');
           req1.setHeader('accept','application/json');
         
  
           req1.setMethod('GET');
           req1.setEndpoint('https://jagadeesh777-dev-ed.my.salesforce.com/services/apexrest/v1/CustomResturl/');
           HttpResponse res1 = h2.send(req1);
           String trimmedResponse = res1.getBody().unescapeCsv().remove('\\');
     JSONParser parser = JSON.createParser(res1.getBody());


List<Contact> insertcontacts=new List<Contact>();
while (parser.nextToken() != null) {
                //Id
               
                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) ){
                    Contact cont;
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'Id')) {
                    // Get the value.
                    parser.nextToken();
                    // Compute the grand total price for all invoices.
                    string sId= parser.getText();
                    cont=new Contact();
                    cont.Id=sId;
                    system.debug('Id@@@' + sId);
                   
                    parser.nextToken();
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
                        (parser.getText() == 'Name')) {
                     
                        parser.nextToken();
                     
                        string sName= parser.getText();
                        cont.LastName=sName;
                       
                    }
                   
                    //Email
                    parser.nextToken();
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
                        (parser.getText() == 'Email')) {
                       
                        parser.nextToken();
                       
                        string sEmail= parser.getText();
                        cont.Email=sEmail;
                     
                    }
                   
                insertcontacts.add(cont);
                }
    
               
                }
    }
    
   
    Insert contList;

Friday, March 10, 2017

Simple Caluclator using lightning components


Step 1: Create a component with the name caluclator, once you save this it becomes caluclator.cmp

Step 2: Copy the below code and paste it in the component section of the bundle.



<aura:component >
    <aura:attribute name="num1" type="Integer"/>
    <aura:attribute name="num2" type="Integer"/>
    <aura:attribute name="num3" type="Integer"/>
    <ui:inputNumber label="Number 1" value="{!v.num1}"  />
    <ui:inputNumber label="Number 2" value="{!v.num2}"   />
    <aura:attribute name="addbo1" type="Boolean" default="false"/>
    <aura:attribute name="subbo1" type="Boolean" default="false"/>
    <aura:attribute name="mulbo1" type="Boolean" default="false"/>
    <aura:attribute name="divbo1" type="Boolean" default="false"/>
    <aura:attribute name="refreshbo1" type="Boolean" default="false"/>
   
   
   
<aura:if isTrue="{!v.addbo1}">
    Addition of Two Numbers is :  {!num3}
    <ui:outputNumber value="{!v.num3}"/>
</aura:if>
   
    <aura:if isTrue="{!v.subbo1}">
     Substraction of Two Numbers is :  {!num3}
         <ui:outputNumber value="{!v.num3}"/>
</aura:if>
   
    <aura:if isTrue="{!v.mulbo1}">
    multiplication of Two Numbers is :  {!num3}
         <ui:outputNumber value="{!v.num3}"/>
</aura:if>
   
    <aura:if isTrue="{!v.divbo1}">
    Division of Two Numbers is :  {!num3}
         <ui:outputNumber value="{!v.num3}"/>
</aura:if>
   
   
     <ui:button press="{!c.Add}" label="Addition" />
     <aura:if isTrue="{!v.refreshbo1}">
     <ui:button press="{!c.Refresh}" label="Refresh" />
    </aura:if>
    <ui:button press="{!c.Sub}" label="Substraction" />
 
    <ui:button press="{!c.Mul}" label="Multiplication" />
 
    <ui:button press="{!c.Div}" label="Division" />

   
 
</aura:component>

Step 3: copy the below code and paste it in the controller section of the bundle.

({
Add : function(component, event, helper) {
        var num1=component.get("v.num1");
        var num2=component.get("v.num2");
        var num3=num1+num2;
        component.set("v.num3", num3);
         component.set("v.addbo1", true);
        component.set("v.refreshbo1", true);
            component.set("v.mulbo1", false);
          component.set("v.subbo1", false);
          component.set("v.divbo1", false);
     

},
    Mul : function(component, event, helper) {
        var num1=component.get("v.num1");
        var num2=component.get("v.num2");
        var num3=num1*num2;
        component.set("v.num3", num3);
         component.set("v.mulbo1", true);
          component.set("v.refreshbo1", true);
            component.set("v.divbo1", false);
          component.set("v.subbo1", false);
          component.set("v.addbo1", false);
     

},
    Sub : function(component, event, helper) {
        var num1=component.get("v.num1");
        var num2=component.get("v.num2");
        var num3=num1-num2;
        component.set("v.num3", num3);
         component.set("v.subbo1", true);
          component.set("v.refreshbo1", true);
            component.set("v.mulbo1", false);
          component.set("v.divbo1", false);
          component.set("v.addbo1", false);
     

},
    Div : function(component, event, helper) {
        var num1=component.get("v.num1");
        var num2=component.get("v.num2");
        var num3=num1/num2;
        component.set("v.num3", num3);
         component.set("v.divbo1", true);
          component.set("v.refreshbo1", true);
            component.set("v.mulbo1", false);
          component.set("v.subbo1", false);
          component.set("v.addbo1", false);
     

},
   
     Refresh : function(component, event, helper) {
     
         component.set("v.num1", 0);
          component.set("v.num2", 0);
         component.set("v.divbo1", false);
          component.set("v.mulbo1", false);
          component.set("v.subbo1", false);
          component.set("v.addbo1", false);
           component.set("v.refreshbo1", false);
     

}
})

Step 4: Save the component.

Step 5: Create a new lightning application and replace the code with the below code

<aura:application >
    <c:caluclator />
</aura:application>

Step 6: Save the application and then click on preview.


Thursday, February 23, 2017

Salesforce to Salesoforce Rest API

===============================
vf page: need to provide username, pwd+securitytoken
==================================

<apex:page controller="othersfaccounts" standardStylesheets="true">
<style type="text/css">
.errorMsg{
    font-size:0.8 em;
    color:red;
}
</style>
<apex:pageBlock >
<apex:form >
<apex:outputLabel value="UserName : " for="userName"/>
<apex:inputText required="true" id="userName" value="{!userName}" />
<br />
<apex:outputLabel value="Password : " for="pwd"/>
<apex:inputsecret id="pwd" value="{!pwd}"/>
<br />
<apex:commandButton id="getRecords" value="Get Records" action="{!fetch}" rerender="wrapper" status="waitStatus" />
<apex:actionStatus startText="Requesting..." stopText="" id="waitStatus"/>
<hr />
<apex:outputPanel id="wrapper">
<div class="errorMsg" style="display:{!displayError}"> {!errMsg} </div>
<apex:pageBlockTable value="{!acc}" var="account" id="accTable" rowClasses="odd,even" styleClass="tableClass">

    <apex:column >
        <apex:facet name="header">Account Name</apex:facet>
         <apex:outputText value="{!account.name}"/>
    </apex:column>

    <apex:column >
        <apex:facet name="header">Created By</apex:facet>
         <apex:outputText value="{!account.CreatedBy.FirstName}"/>
    </apex:column>

    <apex:column >
        <apex:facet name="header">Phone</apex:facet>
         <apex:outputText value="{!account.Phone}"/>
    </apex:column>

</apex:pageBlockTable>
</apex:outputPanel>
</apex:form>
</apex:pageBlock>
</apex:page>
==================================================
Integration ccontroller
==================================================

public with sharing class othersfaccounts {

    //Login Domain May be test, prerellogin.pre
    String LOGIN_DOMAIN = 'chitti-sp-testing-dev-ed.my';
    public String pwd{get;set;}
    public String userName{get;set;}
    public List<Account> acc{get;set;}
    public String errMsg{get;set;}
    public String displayError{get;set;}

    public othersfaccounts()
    {
        displayError = 'none';
    }

    public void fetch()
    {
        errMsg  = 'Some error occurred, please try again';
        try
        {
        //-----------------------------------
        // Login via SOAP/XML web service api
        //-----------------------------------
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://' + LOGIN_DOMAIN + '.salesforce.com/services/Soap/u/37.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>' + pwd+ '</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 10 accounts via REST API
        //---------------------------------
        final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v37.0/query/');
        theUrl.getParameters().put('q','Select a.Phone, a.Name, a.CreatedBy.FirstName, a.CreatedById From Account a limit 10');
        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();

        acc = (List<Account>) parser.readValueAs(List<Account>.class);
        }
        catch(Exception e)
        {
            displayError = 'block';
        }

    }
}

Salesforce to salesforce SOAP API

Salesforce Org to Salesforce Org Integration using soap api(Partner wsdl)



Steps:

1) Download the partner wsdl of one org(destination).
setup --> Develop --> api --> Click on Generate Partner WSDL.



Save the file as xml for example partnerwsdl.xml
sample wsdl will be as follows



2)Open another sf org(source).
Goto setup -->develop --> Click on Apex Classes --> click on Generate from WSDl button.


select the downloaded xml file and then click "parse wsdl" button.
It results in generation of four classes.
1)sobjectPartnerSoapSforceCom
2)faultPartnerSoapSforceCom
3)partnerSoapSforceCom
4)AsyncPartnerSoapSforceCom.

3)Now you can interact with partner or destination org as follows.

Open Developer console and place the below code in execute anonymous block.

partnerSoapSforceCom.Soap  s=new partnerSoapSforceCom.Soap ();
String username = 'username';
String password = 'password+securitytoken';

partnerSoapSforceCom.LoginResult lr = s.login(username, password);
s.SessionHeader = new partnerSoapSforceCom.SessionHeader_element();
s.endpoint_x=lr.serverurl;
s.Sessionheader.sessionid = lr.sessionid;
s.getUserInfo();
system.debug('sssssssssssssss'+s.getUserInfo());