Sunday, February 25, 2018

Salesforce Lightning: Application Events (Sample Siri)

Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All components that provide a handler for the event are notified.


Step 1 : create Application event

/* Use type="APPLICATION" in the <aura:event> tag for an application event. For example, this c:appEvent application event has one attribute with a name of message. */

===============================
ApplicationCommunication  Event
================================


<aura:event type="APPLICATION" description="Discussion between multiple Components" >
 
    <aura:attribute name="mesg" type="string" />
 
 
</aura:event>


Step 2:  Create Source Component

/*A component registers that it may fire an application event by using <aura:registerEvent> in its markup. The name attribute is required but not used for application events. The name attribute is only relevant for component events. This example uses name="appEvent" but the value isn’t used anywhere.*/

Name: SourceCmp
==================

<aura:component implements="flexipage:availableForAllPageTypes">
 
    <aura:registerEvent name="anyname" type="c:ApplicationCommunication" />
    <aura:attribute name="Display" type="boolean" default="false" />
    <aura:attribute name="greeting" type="string" />
    <lightning:input type="string" label="Enter some data here"  aura:id="inputdata"/>
    <p><lightning:button label="Click here to fire an application event"
        onclick="{!c.fireApplicationEvent}" />
    </p>


</aura:component>

Step 3: copy paste below code in the SourceCmp  client side controller
======
SourceCmp controller side code
========
({
fireApplicationEvent : function(component, event, helper) {
     
        var message=component.find("inputdata").get("v.value");
     
        var appEvent=$A.get("e.c:ApplicationCommunication");
     
        appEvent.setParams({"mesg":message});
     
        appEvent.fire();
     
 

}
})


Step 4: Listener or Handler Markup code

/*Use <aura:handler> in the markup of the handler component.

For example:

<aura:handler event="c:appEvent" action="{!c.handleApplicationEvent}"/>*/

==========
Name: Listener (Handler)
===========
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
    
    <aura:attribute name="receivedevent" type="string"  />
    
    <aura:handler event="c:ApplicationCommunication" action="{!c.handleApplicationEvent}" />
    
     <p>{!v.receivedevent}</p>

    
</aura:component>


Step 5:


==================
Listener client side controller
==================
({
    handleApplicationEvent : function(cmp, event) {
      var Sourcedata= event.getParam("mesg");
        var response="Sorry I did not understand you";
        if(Sourcedata=='Hi')
        {
            response="Hello"
        } 
         if(Sourcedata=='How are you')
        {
            response="Im doing great!!"
        } 

         if(Sourcedata=='How is your course')
        {
            response="Going good"
        } 
         if(Sourcedata=='Do practice after this session')
        {
            response="Sure Thank you !!"
        } 
         if(Sourcedata=='Good Night')
        {
            response="Good night too, sweet dreams !!"
        } 
         if(Sourcedata=='Good Morning')
        {
            response="Good Morning too, have a great day !!"
        } 

            
        cmp.set("v.receivedevent",response);
    }

})


Step 6:  create Application with the below code

<aura:application >
    <c:SourceCmp />
    <c:Listener  />
</aura:application>


Step 7: Instead of above 6th step code I recommend to Surface SourceCmp and Listener  on different parts of the Application builder page. Though there is no connection between these components but still you can create communication  between these two components.



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;