Thursday, May 2, 2019

CI/CD Salesforce model

Hi All,

So many of you are wondring how to have a CI/CD model implemented with Salesforce. There are many options:

  1. SFDC
  2. Custom AppExchange products(using some sort of version controll and handing access to that repository to the app)
  3. Custom
I am going to share a flavor of the 3rd option below.

Your setup needs will be:
  1. Git repository that is published with internet access
  2. Jenkins that is published with internet access 
  3. Ant/JAVA setup within Jenkins
  4. Salesforce creds.
Your working path will be:
  1. Developer connects with git repository and make the code changes and then commit the code in git.
  2. Git will fire Jenkins job that will deploy the code into another org.
Click the below gif to see demo.

Tuesday, February 13, 2018

Salesforce DX initial guide

Salesforce DX is a VCS from alesforce, if you are working on collaborative projects with a multiple developer then you may need to use git along side with DX.

To start we need to have a Dev Hub org, you will use this to control all your scratch orgs, also you will need Salesforce CLI installed in your local machine.

1. Command to login and authenticate your dev hub user.
sfdx force:auth:web:login --setdefaultdevhubusername --setalias devhub
If you have used only "sfdx force:auth:web:login" then use the below comman to set user to default
sfdx force:config:set defaultusername=test-wvkpnfm5z@example.com --global
Note: find the user list: sfdx force:user:list

2. Download the package from dev hub, you may have some other org as a source also.
sfdx force:mdapi:retrieve -r ./mdapipkg -u <username> -k ./package.xml

3. Convert it to DX project style
sfdx force:mdapi:convert --rootdir mdapipkg/unpackaged

4. Create a scratch org
sfdx force:org:create -f project-scratch-def.json -a devhub

5. Check org and user name
sfdx force:org:list

6. Push the local change to scratch org to start development.
sfdx force:source:push -u <scratchusername>
Repeat point 6 when ever you make any changes in local.

7. Pull changes from your scratch
sfdx force:source:pull -u <scratchusername>

Wednesday, November 2, 2016

How to get site user in debug logs Winter17

So after winter17 we cannot see site user debug as a salesforce update.

To enable that we have to set cookies in user browser.

In chrome open inspect element>console and paste this.
Document.cookie="debug_logs;domain=.force.com";

Thursday, July 28, 2016

Apex inputField issue with dataTable,pageBlockTable and repeat

When working with <apex:inputField> inside dataTable,pageBlockTable with wrapper objects you have to use <apex:column> if you donot use it visualforce pahe will result inot an error saying

"<apex:inputField> can only be used with SObjects, or objects that are Visualforce field component resolvable."

To over come this you have to use <apex:inputField> inside <apex:column> or you can use <apex:repeat> instead, when you use <apex:repeat> you have to design the table structure yourself.

Monday, July 18, 2016

Using Salesforce SOAP API in Ajax

Just a small post(its a very old functionality but I just posted it now) for how to create record using /soap/ajax/ in Salesforce. The code can be written in Visualforce page as well as Custom button as javascript.

Reference: SOAP API

Usage:
  1. Can be used to create record like logs or attachments from javascript hence reducing server processing time.
  2. Can query record to check values in page layout buttons.

Friday, July 1, 2016

How to have a image crop functionality in salesforce

Many time there is a custom requirement(generally in community) that a user can upload images, and when they do so there should be a functionality to crop or rotate it. We can achive it by using "corpper.js" Link.

Note: This page will through a viewstate error, due to base64 string size, try using transient variable to solve this.


Thursday, June 30, 2016

How to load Jquery or other scrips by console or lazy loading in page

Hi So the other day I was updating a few checkbox manually and then thought then why not do it by Jquery, as soon as I ran the famous selector and prop function chrome throw me error of undefined.
It was due to no jquery loaded in the context or DOM.
To do this there is a simple trick just open the console and paste the below script.


This can also be loaded in page after some execution or even inside "$( document ).ready() {}".

Friday, June 10, 2016

How to "break" pass by reference in Lightning attributes

Hi,
I resently came by the problem in Lightning Aura development. I was developing a page to show some components on the page, the requirment was that user can deselect some of the rows and then data has to be rearranged accordingly simple right!.

I also thought so the approch I took was to have two list one for the values to display and another to hold the cloned values, so if the user rests all I can replace it with clone values and done. What happen in auro if the two variable are seprate but you filled them using a single source of reference then they are pointing to the same memory and hence if one changes other implecitly chnages. To eleminate this proble I simply used "JSON.stringify".

What this will do is when you have your values from controller to JS component then convert it into a well formated structure and then using "eval" convert it back to object. This will break the pass by  reference problem and two values can be independent.

Sunday, March 27, 2016

How to automate your salesforce deployment using Ant

Recently I was thinking to make automatic deployment mechanism to save time that was invested in weekly deployments. So after scratching the surface of Ant Migration Tool I cam up with this script to automatically extract and deployment class and trigger from one org to another.

Option 1-
Step 1. Must have JDK 1.6 or higher
Step 2. Install Ant to your machine use this "http://ant.apache.org".
Step 3. Download Salesforce Ant Migration ZTool Jar package.
Step 4. Create/Clone two folder using the sample folder in the zip.
Step 5. Provide Username password to both the Build.property files.
Step 6. Use this code and save it to Auto.bat in any location
ECHO Retrieve and Deployment auto script started..
cd\
cd <Path to>\Retrieve Meta
start /W ant retrieveUnpackaged ^&^& exit
Xcopy  /S /I /E /Y "<Path to>\Retrieve Meta\retrieveUnpackaged"  "<Path to>\Deploy Meta\codepkg"
ECHO Retrieve file copied to Deployment folder..
cd\
cd <Path to>\Deploy Meta
start /W ant deployCode ^&^& exit
ECHO Retrieve and Deployment auto script stoped..
PAUSE Press Enter to close

Where <Path to> is the path where you extracted the Ant Migration Tool and cloned folders.

Option 2-
Have a ant build.xml configured with two targets first for retrieve and second for deployment and link them inside another target like <target name="all" depends="retrieve, deploy">
</target> then open cmd and run this
ant -f build.xml all

Monday, September 14, 2015

Convert your Metadata object structure to "XLS"

Ok so today one of my requirement was to convert the whole Metadata object structure to XLS information for a client and so I maked a small java program to do it.

Note: the file have to be downloaded by using force.com IDE and just place it in the new location and run this code:
What it will do is to convert the .object files into a single XLS file to be read as a object definition, its use full if you need to constantly use XLS for reporting and audit.
Download link: HERE

Thursday, October 16, 2014

How to use Streaming API in visualforce Salesforce

Ok so as per new enhacnement Slaesforce has introduced streaming API in force.com. The cool thing is that it works on "Comet" model, its accually a long-held HTTP request model. So if a connection is open it will get the new updates through polling. The server will pust the new data into the stream and thus we will get notification in page without even using page reload or API request.


Result:

Hope this helps you!!

Tuesday, October 7, 2014

How to get all property of a javascript [object object]

Ok so sometime when usings others code in javascript me might not be knowning the property that returning object has. So to get the property just use this code after initilizing and record all the available property and values and then use accourdingly.

Option 1:
for(var key in conn) {

    var value = key +" : "+ conn[key]; console.log("***"+value); 
} 
Option 2:
console.log(conn);  

Hope this helps you!!

Sunday, October 5, 2014

How to use workflow outbound message to send xml to other systems

Ok so I was not finding any good articals to learn how to use outbound message in Salesforce.

So to begin just create a workflow at your desired object.
Now create a action of type "Outbound Message" and give the field information.
Now in the "Endpoint URL" give the URL you want to post data to eg: http://example.in/wscd.asmx etc.
Now give the fields in the multy select box to be sent with request.

And this the output you will receive on the end point.













Salesforce automatic gives it a XML formate and the reciver endpoint service must parse this to get the posted data.

Hope this helps you!!

Thursday, October 2, 2014

How to understand and use Interface, Abstract and Virtual definition modifier in apex Salesforce

Ok so this is a very conceptual module in apex or OOPs programming.

Interface is a which none of the methods have been implemented but when its implemented then it is mandatory to define all of its declared method in the implementing class. Also we cannot define any fields in interface and all the method are final and pubic.

Example:

public interface custom_Interface{
    void CallFirst();
    Void CallSecond();
}
public class Implement_custom_Interface implements custom_Interface{
    public void CallFirst(){
        //
        system.debug('***First**');
    }
    public void CallSecond(){
        //
        system.debug('***Second**');
    }
}

Abstract class is class with only declaration and no definition but its mandatory to override all the method.

Example:

public abstract class custom_Abstract{
    public abstract string AbstractFirst();
    public abstract string AbstractSecond();
    public void noReturn(){
    }
}
public class Implement_custom_Abstract extends custom_Abstract{
    public override string AbstractFirst(){
        system.debug('***From Abstract Extends Class***');
        return null;
    }
    public override string AbstractSecond(){
        system.debug('***From Abstract Extends Class***');
        return null;
    }
}

Virtual class is having definition of the method and if you need you can override the method, but its not mandatory to implement all the methods.

Example:


public virtual class coustom_Virtual{
    public virtual void OverFirst(){
        system.debug('****From  Defination****');
    }
    public virtual void OverSecond(){
        system.debug('****From  Defination****');
    }
}
public class Implement_coustom_Virtual extends coustom_Virtual{
    public override void OverFirst(){
        system.debug('!!!From  Declairation!!!');
    }
}
Hope this helps you!!

Wednesday, September 24, 2014

How to display an Image in richtext area field when Image is in attachments

Ok so now if I want to display the same image that is in the attachment of a record? Confused I know as images are stored by salesforce in the back end are not available by simple URL access an Eg:


<img alt="User-added image" height="281" src="https://c.ap2.content.force.com/servlet/rtaImage?eid=00390000018kf3r&amp;feoid=00N9000000XXXX&amp;refid=0EM9000000XXX" width="500"></img>
This is how salesforce saves the image in the rich text box and now if we need to save any kind of image we can, as we just need the 18 digit Id of the saved image.

An attachment has a 18 digit Id and we can use this as Eg:


<img src="https://c.ap2.content.force.com/servlet/servlet.FileDownload?file=00P9000000DXXXX" width="500" height="300"></img>
Wola!! now we can save any image to richtext area form apex code or by query editor. give it a try and ask me if you have any questions.

Hope this helps!!

Note: Refer - http://ankit-rustagi.blogspot.in/2012/10/to-insert-image-into-rich-text-area.html

Tuesday, September 23, 2014

How to display a image if you have Bas64 sting on a visualforcfe page

Ok so recently I got a requirement that the image is saved in a Base64 format and when it is displayed it should be displayed as image.

What? Right and here is a small trick to do the job.

<img alt="<image_Name>" src="data:image/<image_File_Extension>;base64, <base64_Image_String>"></img>
http://developer.force.com/cookbook/recipe/converting-a-rich-text-area-fields-image-for-api-upload

Hope this helps!!

Thursday, August 28, 2014

How to do JSON parsing in Apex Visualforce

Ok so today we will be looking into the Json parsing. Json is "Javascript Object Notation" a new form of format which is widle used over the http responce in webservices. It is structured and can contain data in human readable format.

To make json data salesforce provide some standard class called as System.JSON. We will be using this class to parse and then un parse the data in json.

Parsing:

  1. Create a visualforce page with controller.
  2.  Now copy this code to make a wrapper class holding name,id and phone fields
    //Subclass : Wrapper Class 
        public class Accountwrap {
            //Static Variables 
            public string id;
            public string name;
            public string Phone;
            
            //Wrapper  Class Controller
            Accountwrap(string Phone, string name, string id) {
                this.Phone = Phone;
                this.name = name;
                this.id = id;
            }
        }
  3. Now to parse this wrapper class list into a json string use this code.
    public void getlstAccount(){
            List < Accountwrap > lstwrap = new List < Accountwrap > ();
            List < account > lstacc = [SELECT Id, Name, Phone FROM Account limit 2];
            for (Account a: lstacc) {
                Accountwrap awrap = new Accountwrap(a.Phone,a.name,a.id);
                lstwrap.add(awrap);
            }
            strJson = JSON.serialize(lstwrap);
        }
  4. strJson is a public string and will get the json string,
Un-Parsing:
  1. To convert the json string we will use the same wrapper class to provide structure to the values.
  2. To un parse the string use this code
    public static List<Accountwrap> parse(String str) {
            system.debug('*****str*****'+str );
            JSONParser parser = JSON.createParser(str);
            system.debug('*****parse*****'+parser );
            List<Accountwrap> jsonstatLst = new List<Accountwrap> ();
            while (parser.nextToken() != null) { System.debug('Current token: ' +  parser.getCurrentToken() + '****JSONToken.START_ARRAY****'+JSONToken.START_ARRAY);
                if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
                    while (parser.nextToken() != null) {
                        // Advance to the start object marker to
                        //  find next invoice statement object.
                        if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                            jsonstatLst.add((Accountwrap)parser.readValueAs(Accountwrap.class));
                            parser.skipChildren();
                        }
                    }
                }
            }
            return jsonstatLst;
        }
  3. jsonstatLst is a List of type wrapper class and the method can populate any list of the same type with data in wrapper object form.
Hope this helps you!!

Wednesday, August 27, 2014

How to bootstrap with Visualforce

Ok so today I am going to show you a small and simple example of how to get started with bootstrap in visualforce. Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web. So now first thing first:

  1. Download bootstrap lib zip file from "http://getbootstrap.com/" and upload it to your custom setting by name "Bootstrap".
  2. Now create a visualforce page name "Bootstrap_Mobile_CreateAccount".
  3. And include the bootstrap scripts as :

<!-- Load script here -->
    <apex:stylesheet value="{!URLFOR($Resource.Bootstrap, 'bootstrap-3.2.0-dist/css/bootstrap-theme.min.css')}"/>
    <apex:stylesheet value="{!URLFOR($Resource.Bootstrap, 'bootstrap-3.2.0-dist/css/bootstrap.min.css')}"/>
    <apex:includeScript value="https://code.jquery.com/jquery.js"/>
    <apex:includeScript value="{!URLFOR($Resource.Bootstrap, 'bootstrap-3.2.0-dist/js/bootstrap.min.js')}"/>
    4.   Now create div and give the class of bootstrap as shown here
<div class="container">
 <br/>
 <div class="panel panel-primary">
  <div class="panel-heading">
   <h3 class="panel-title">Create Account</h3>
  </div>
  
  <div class="panel-body">
   Details:
   <div class="row">
    <div class="col-md-4"><input id="inp1" type="text" placeholder="Account Name" class="form-control"/></div>
    <div class="col-md-4"><input id="inp2" type="text" placeholder="Description" class="form-control"/></div>
    <div class="col-md-4"><input id="inp3" type="text" placeholder="Phone" class="form-control"/></div>
   </div>
   <br/>
   <br/>
   <button class="btn btn-lg btn-primary btn-block" type="submit" onclick="createAcc();">Save</button>
  </div>
 </div>
</div>
     5.   Now provide this <javaScript> to the page to we can save the records.
<script>
 Visualforce.remoting.timeout = 120000; // Set timeout at page level
 var $j = jQuery.noConflict();        

 function createAcc(){
  $j('#basicModal2').modal('show');
  var accName= $j('#inp1').val();
  var accDes= $j('#inp2').val();  
  var accPhn= $j('#inp3').val();          
  Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.Bootstrap_Mobile_CreateAccountCon.createAccount}',accName,accDes,accPhn,handleResult);  
 } 
 function handleResult(result, event){
  if (event.status) {
   alert(result);
  } 
      
 }             
</script>  
6. Now create a controller and in that create this javascriptRemoting method
@RemoteAction
global static string createAccount(String accName, String accDes, String accPhn){
 Account acc = new Account();
 acc.name = accName;
 acc.Description = accDes;
 acc.Phone = accPhn;
 insert acc;
 return 'Success';
}
That is it, You have created a visualforce page that is using bootstrap css for view and apex controller for saving the records.

PS: For different type of element you can use different class as:
CheckBox:
<div class="checkbox col-md-4">
 <label>
   <input type="checkbox"> Check Box</input>
 </label>
</div>
//get the checkbox values as this or you can also get a array of objects and use .each
//for multiple checkboxes id starting with inp4
function checkId(){
   var inpVal= $j('#inp4').prop('checked');
   alert(inpVal);
}

Hope this helps you!!

How to use apex:dynamicComponent in visualforce page to generate DOM elements at run time

Ok so today I am sharing the code for how to generate apex component dynamically. Salesforce has introduced a new feature call as "apex:dynamicComponent", what this does is it will introduce visualforce markup in the page from controller just like a dynamic binging.

To do this use this in the visualforce page:
<apex:dynamicComponent componentValue="{!outPanel}"/>
Now in the class write this:
Public transient Component.Apex.OutputPanel outPanel{get;set;}
Public List<sObject> vNewLst{get;set;}
public void getdynPan(){      

vNewLst = database.query('Select Id,Name from Account limit 100');    
outPanel = new Component.Apex.OutputPanel();   
Component.Apex.DataTable datatable = new
Component.Apex.DataTable(var='row');    
datatable.expressions.value='{!vNewLst}';    
list<String> displayFieldLst= new list<String>{'Id','Name'};    
Component.Apex.column clm;   
Component.Apex.OutputText outText;      
  for(string s: displayFieldLst){          
    clm = new Component.Apex.column(headerValue= '' + s + '');         
    outText = new Component.Apex.OutputText();          
    outText.expressions.value = '{!row[\'' + s + '\']}';         
    clm.childComponents.add( outText );      
    datatable.childComponents.add( clm );
  }  
  outPanel.childComponents.add( datatable );
}

What this code will do it will create a output panel and bind a datatable inside it with Id and Name columns and then display it on the page.

Hope this will help you!!

How to use apex:dynamicComponent in visualforce page to generate DOM elements at run time

Ok so today I am sharing the code for how to generate apex component dynamically. Salesforce has introduced a new feature call as "apex:dynamicComponent", what this does is it will introduce visualforce markup in the page from controller just like a dynamic binging.

To do this use this in the visualforce page:
<apex:dynamicComponent componentValue="{!outPanel}"/>
Now in the class write this:
Public transient Component.Apex.OutputPanel outPanel{get;set;}
Public List<sObject> vNewLst{get;set;}
public void getdynPan(){      
vNewLst = database.query('Select Id,Name from Account limit 100');    
outPanel = new Component.Apex.OutputPanel();   
Component.Apex.DataTable datatable = new Component.Apex.DataTable(var='row');    
datatable.expressions.value='{!vNewLst}';    
list<String> displayFieldLst= new list<String>{'Id','Name'};    
Component.Apex.column clm;   
Component.Apex.OutputText outText;      
for(string s: displayFieldLst){          
clm = new Component.Apex.column(headerValue= '' + s + '');         
outText = new Component.Apex.OutputText();          
outText.expressions.value = '{!row[\'' + s + '\']}';         
clm.childComponents.add( outText );      
datatable.childComponents.add( clm );
}  
outPanel.childComponents.add( datatable );
}
What this code will do it will create a output panel and bind a datatable inside it with Id and Name columns and then display it on the page.

Hope this will help you!!