Thursday 5 October 2017

                   Batch example scenario

Consider two fields x and y. we have already uploaded or inserted so many  Account records. At that time we haven't written any trigger or we were not aware of the future requirement.

Requirement:  If the x  value is  1  we have to update 10 in DB, if x value is  2 we have to update 20 and so on [code is self-explanatory].  

we might have a huge number of records with these unique values (1,2,3,4) and while processing in DB should be mapped to corresponding values like 20,30,40,50.

As of know, only 4 unique numbers starting from 1. 

for example:
x ---->y
1---->20
2---->30
3---->40
4---->50



Best approach is batch class

global class MapConceptUpdate implements Database.Batchable<sObject>{
    global Database.QueryLocator start(Database.BatchableContext BC)  {
        string query='select id,x_value__c,y_value__c from Account';
        return database.getqueryLocator(query);
    }
    global void execute(Database.BatchableContext BC,List<Account> scope){
        map<double,double> mapval=new map<double,double>();
        mapval.put(1,20);
        mapval.put(2,30);
        mapval.put(3,40);
        mapval.put(4,50);
       
        List<Account> aclist=new List<Account>();
        for(account ac:scope){
            if(ac.x_value__c!=null && !mapval.isEmpty()&& mapval.containsKey(ac.x_value__c)&&mapval.get(ac.x_value__c)!=null){ 
               ac.y_value__c=mapval.get(ac.x_value__c);
               aclist.add(ac);
            }   
        }
        if(!aclist.isEmpty()){
             update aclist; 
        }
       
    }
    
    global void finish(Database.BatchableContext BC) {
        
    }
}

               System.debug  is not showing in debug logs


step 1:
                  In your debug level check in Apex code debug is set
                setup--->debuglevel--->Apexcode-->debug set
Step 2:
               Debug log size if its 2MB <= then SF skip the Debug statement in that case set all unwanted flag to none so that it will reduce your debug size and then you can see the debug.

                                     Batch Apex

------------------------------------------------------------------------------------------------------------------------
Batch Apex is used to run large jobs (think thousands or millions of records!) that would exceed normal processing limits. Using Batch Apex, you can process records asynchronously in batches (hence the name, “Batch Apex”) to stay within platform limits. If you have a lot of records to process, for example, data cleansing or archiving, Batch Apex is probably your best solution.


Start method:
       The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects to be passed to the interface method execute.

Execute Method:
      The execute method is called for each batch of records passed to the method. Use this method to do all required processing for each chunk of data.

Finish Method
  The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.
       Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each.
The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.

--------------------------------------------------------------------------------------------------------------------------
Useful Links:

1. http://www.infallibletechie.com/2012/05/apex-scheduler.html

2. https://trailhead.salesforce.com/en/modules/asynchronous_apex/units/async_apex_batch

3. http://blog.shivanathd.com/2013/01/how-to-write-batch-class-in.html
-------------------------------------------------------------------------------------------------------------------------

global class BatchAccountUpdate implements Database.Batchable<sObject> {
   global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id,Name FROM Account';
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext BC, List<Account> scope) {
         for(Account a : scope)
         {
             a.Name =  a.Name+'Salesforce King';
           
         }
     
         update scope;
    } 
 
    global void finish(Database.BatchableContext BC) {
    }
}
--------------------------------------------------------------------------------------------------------------------------
global class BatchScheduleAccount {
    global void execute(SchedulableContext sc)
    {
        // Implement any logic to be scheduled
     
        // We now call the batch class to be scheduled
        BatchAccountUpdate b = new BatchAccountUpdate ();
     
        //Parameters of ExecuteBatch(context,BatchSize)
        database.executebatch(b,200);
    }
}
------------------------------------------------------------------------------------------------------------------------

Test class for Batch Apex:
@isTest
public class BatchAccountUpdate_Test {
    public static testmethod void batchMethod(){
        List<Account> aclist=new List<Account>();
        for(integer i=0;i<=200;i++){
            Account ac=new Account();
            ac.name='TEST'+i;
            aclist.add(ac);
        }
        insert aclist;
     
        Test.startTest();
        BatchAccountUpdate b=new BatchAccountUpdate();
        // database.executeBatch(b);
        Database.QueryLocator ql = b.start(null);
        b.execute(null,aclist);
        b.Finish(null);
        Test.stopTest();
    }
 
}
--------------------------------------------------------------------------------------------------------------------------
Test class for scheduler class:
@isTest
public class BatchScheduleAccount_Test {
    public static testmethod void batchMethod(){
        test.startTest();
        BatchScheduleAccount  ac=new BatchScheduleAccount();
        ac.execute(null);
        test.stopTest();
    }

}
------------------------------------------------------------------------------------------------------------------------

Tuesday 3 October 2017

    Setting Read-Only Mode for an Entire Page

   To display a page in read-only mode you can use page attribute as follows:

<apex:page controller="myController" readOnly="true">
<apex:page>

Other advantage is query limit is getting increased from 50,000 rows to 1,000,000 rows.
In addition to querying many more rows, the readOnly attribute also increases the maximum number of items in a collection that can be iterated over using components such as <apex:dataTable><apex:dataList>, and <apex:repeat>. This limit increased from 1,000 items to 10,000. 
Special Note: 
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_readonly_context_methodlevel.htm

Sunday 24 September 2017

DML not allowed in Constructor in Salesforce


Salesforce has blocked this due to security issues. If you want to do DML operation during VF page loading, use action attrirbute in <apex:page>. Call a method from the action in which DML operation is allowed.


Special Note:
https://salesforce.stackexchange.com/questions/28833/why-is-dml-not-allowed-in-constructor

Sunday 3 September 2017

                                 Future Method:


A future method runs in background, Asynchronously
each method is queued and executes when system resource becomes available
To define future method simply annotate it with future annotation
========================================================
global class FutureClass{
@future
public static void myFutureMethod(){

}
}
=======================================================
future Method:
Method with future annotation

1.Must be static methods
2.and only return a void type

specified parameter must be primitive data types
or arrays of primitive data type


It doesn't except sObject as parameter. sObject might change between the time you call the method and time it executes

To work with sObject that already exist in the database pass the sObject ID
=============================================================
Simple Code Snippets:

global class FutureMethodRecordProcessing{
   @future
public static void processRecords(List<id>recordids){

List<account> accts= [SELECT name FROM account WHERE id in:recordids];

}
}
==============================================================

                        Queueable Apex:


Take control of your asynchronous process by using queueable interface

To monitor Queueable Apex:
setup-->Apex Jobs

Queueable jobs are similar to future methods in that they are both queued for execution

Additional benefits:
1.Getting the id of the job
2.using non primitive datatypes
3.chaining Jobs

================================================================
public class c1 implements Queueable{

public void execute(QueueableContext context){
account a=newaccount();
a.name='test';
a.phone='8147285030';
insert a;
}

}

=================================================================
//how do you call this class

ID jobid=system.enqueueJob(new c1());
=================================================================

                           Apex scheduler:

Suppose we want to execute job at regular interval.

=================================================================
public class s1 implements  Scheduleable{

public void execute(ScheduleableContext  sc){
//code here
}

}
=================================================================

Please Note:

1.Code executes at the specified time
2.Actually execution may be delayed based on service availability
3.you can only have 100 scheduled apex at one time

goto apex classes-->scheduled apex--> you can specified time as well and start date & end date

Sunday 13 August 2017

                   Remove duplicate items from a List:

Today I'am going to demonstrate how to remove duplicate values in List. Please add below code in your anonymous window and check how it works.

List<integer> orginalresult=new List<integer>();
orginalresult.add(1); // 0th position
orginalresult.add(2);//1st position
orginalresult.add(2);
orginalresult.add(10);
orginalresult.add(11);
orginalresult.add(3);
orginalresult.add(4);
orginalresult.add(4);
orginalresult.add(1);
orginalresult.add(5);
system.debug('@@@ originalList@@@'+orginalresult);
set<integer> setresult=new set<integer>();
List<integer> Listresult=new List<integer>();
setresult.addAll(orginalresult);
system.debug(setresult);
Listresult.addAll(setresult);
system.debug(Listresult);

Problem: when converted to a Set and then back to a List using addAll(), the order doesn't remain.
Solution:
//To maintain order, you need to iterate over the elements:
for(integer s:orginalresult){
    if(setresult.add(s)){
        Listresult.add(s);
    }
    }
system.debug('@@@ListResult @@@@'+Listresult);   

Wednesday 2 August 2017

Using Apex:Variable in Visualforce to control rendering of HTML Markup


We mostly use apex:variable tag for declaring complex expressions or variables in visual force page. But the same can be used very easily to control the rendering too.



<apex:page controller="ApexVarController1">
<div>
        <!-- apex:variable tag to control the rendering for Markup --> 
<apex:variable
value="anything will go here" var="flag"
rendered="{!flag}">
<h1> Flag value is true </h1><br />
</apex:variable> 
<!-- apex:variable tag used to not render for a Markup --> 
<apex:variable value="anything will go here" var="flag1" rendered="{!flag1}">
<h1>Flag value is false</h1><br />
</apex:variable>
</div>
</apex:page>
--------------------------------------------------------------------------------------------------
public class ApexVarController1 {
    public boolean flag { get;set;}
    public boolean flag1{get;set;}
    
    public ApexVarController1 (){
       flag=true;
       flag1=false;
    }

}
--------------------------------------------------------------------------------------------------------

Tuesday 18 July 2017

             apex:relatedList

A list of Salesforce records that are related to a parent record with a lookup or master-detail relationship.
<apex:page standardController="Account">
    <apex:pageBlock>
        You're looking at some related list of--->{!account.name}:
        <apex:relatedList list="Opportunities" />
        <apex:relatedList list="Contacts"/>
        <apex:relatedList list="Cases"  />
    </apex:pageBlock>
</apex:page>


Special Note:
           apex:relatedList' component cannot be nested within form tags

Sunday 16 July 2017

                                    FREEZE USERS IN SALESFORCE

When administering Salesforce, you can at times run into scenarios where a particular users’s account should no longer have access. An example of that is when you have reason to believe that a user’s account has been compromised or someone has just left the company and you want to prevent them from logging in. Normally you would just disable the user; however, if the user is part of a custom heirachary field - there are more steps involved. A nice solution in the meantime us to just use the "Freeze" function.

After the user is frozen - the Freeze button changes to an Unfreeze button which performs (well, you get the idea).
Note: When you freeze a user, it does not free up a user license. In order to actually free up a license you have to perform an actual deactivation of the user.


For more Information please refer  Link:
                      http://blog.shivanathd.com/2013/10/Freeze-User-In-Salesforce.html

Thursday 13 July 2017

Tricky sales force Questions 

1. How to delete the User from Salesforce
  salesforce does not allow to delete any user, however you can deactivate the user.

2.If one object in Salesforce have 2 triggers which runs “before insert”. Is there any way to control the sequence of execution of these triggers?

 Salesforce.com has documented that trigger sequence cannot be predefined. As a best practice create one trigger per object and use comment blocks to separate different logic blocks. By having all logic in one trigger you may also be able to optimize on your SOQL queries.

3.How to enable truncate custom object feature in Salesforce ?
Ans : Navigate to “App Setup | User Interface” and select “Enable Custom Object Truncate”.

Sometimes while deleting record it gives error “Object cannot be Deleted”. What is the reason for this kind of error ?

This is generic error message prompted by Salesforce many times, which is not well informative. To get informative message, we can try to delete same record in “Developer Console”. In Developer Console Debug log, we will get exact error message.

Interesting !!!

Example:
Lets say there is one record which is parent of more than 2000 records and grand parent of 5000 records. In such scenario from developer console it gives error something like “record cannot be deleted because it has many associated objects” However in User Interface, it will just display that “Object cannot be deleted."


4.Why CSS is not working in PDF created by Visualforce ?

1.Use “apex:stylesheet” tag to import external CSS file
2.Wrap “Style” tag inside “Head” tag in Visualforce
You have to cross verify the things.If you mentions these propery your css should work

5.whats Test.isRunningTest() ?
Use Test.isRunningTest() in your code to identify that context of class is Test or not. You can use this condition with OR (||) to allow test classes to enter inside code bock. It is very handy while testing for webservices, we can generate fake response easily.


                                                                                                                          Continues ...

Converting Lowercase string to Uppercase & Upper case string to Lower case

/* Here I'am converting lower case to Uppercase  */

string x='ajay';
string uppercase=x.touppercase();     //Converting string to Upper case
system.debug('uppercase ====>'+uppercase);

/* Here I'am converting Uppercase to lower case */
string y='SACHIN';
string Lowercase=y.tolowercase();
system.debug('lowercase====>'+Lowercase);

How to get all Salesforce records even from recycle bin or Achieved Activities using SOQL query?


we cannot do it directly within the Query Editor of developer console.If I run the query in query editor what will happen?!!....I hope you got the answer. But there's a workaround for we can test it  in Developer Console. The workaround is to use the "Execute Anonymous Window".

1. Open "Enter Apex Code" window by selecting "Debug" -> "Open Execute Anonymous Window" menu
2. Enter your query there and output the result to the log. Check the "Open Log" checkbox.
List<contact> clist = [SELECT name FROM contact ALL ROWS];
System.debug(JSON.serialize(clist));
3. Click "Execute" to run your code and check the log file for your result.

Special Note:
               Deleted data is stored in the Recycle Bin for 15 days.


Interesting Link:
                  https://salesforce.stackexchange.com/questions/4020/whats-the-actual-meaning-of-all-rows-in-soql

Wednesday 5 July 2017

 Tricky Error : Cannot Create Master-Detail Relationship

                                        Great things are done by a series of small things brought together. 
                                                                                                                         -Vincent Van Gogh


Some times we will get below error message while creating master detail relationship..

whats that error massage?

"You cannot create a new Master-Detail relationship on an existing custom object if records already exist. You must first create a Lookup relationship, populate the lookup field with data in all records, and then change the relationship type to Master-Detail. "

Have you encounter this error before then its great!!!!. Today I'am going to explain solution about that error

Tricky solution:

Master - Detail relationship requires that the Detail Record (Child) ALWAYS have a Master (Parent) record since the detail record inherits security and ownership from the parent record.
Therefore, if you want to create a Master - Detail relationship between existing objects, you need to make sure that all the existing records for the child object have a lookup value to the parent object BEFORE you can create the Master Detail relationship.

1. Create a lookup from the child object to the parent object.
2. Populate ALL the records with a valid lookup value to the parent.
3. Change the Lookup relationship to a Master - Detail relationship. This is only allowed if ALL RECORDS HAVE A VALID LOOKUP.

Use this query to confirm to check if child record exist arent:
SELECT count()  from Child_object__c;


For detailed Information Visit Below Link:
http://www.tutorialkart.com/salesforce/cannot-create-master-detail-relationship/

Tuesday 4 July 2017

What is a System.runAs() Method in Apex?

Generally, all Apex code runs in system mode, and the permissions and record sharing of the current user are not taken into account. The system method, System.runAs(), lets you write test methods that change user contexts to either an existing user or a new user. All of that user’s record sharing is then enforced. You can only use runAs in a test method. The original system context is started again after all runAs() test methods complete.

Example :

System.runAs(Annappa) {

// The following code runs as user 'Annappa'

System.debug('Current User: ' + UserInfo.getUserName());

System.debug('Current Profile: ' + UserInfo.getProfileId()); }

// Run some code that checks record sharing

}
Special Note:
                       Please check these two Links:

https://salesforce.stackexchange.com/questions/88642/system-runasnew-userid-userinfo-getunserid

https://salesforce.stackexchange.com/questions/13318/error-mixed-dml-operation-on-setup-and-non-setup-objects

I hope you enjoyed the post :)

Monday 3 July 2017

System and User Mode in Sales force

System mode -


Its running apex code by ignoring user's permissions. So if logged in user does not have create permission but they will able to create a record.
Apex code has access to all objects and fields, sharing rules aren't applied for the current user. 
All apex code run in system mode. It ignores user's permissions. Only exception is anonymous blocks like developer console and standard controllers.

User mode - 


Its running apex code by respecting user's permissions and sharing of records. So, logged in user does not have create permission they are not able to create a record.
Only standard controllers and anonymous blocks like developer console run in user mode.


Special Note:

  Please Visit the  below Links.
                                                http://www.tgerm.com/2011/03/trigger-insufficient-access-cross.html

 


Does option “Re-evaluate Workflow Rules after Field Change” exist in process builder?"


Yes its possible in Process Builder.

How to do that?

You can do this while adding the object. If you check the Yes checkbox under Allow process to evaluate a record multiple times in a single transaction. the record will be re-evaluated maximum of 5 times in same transaction.

Hope it helps.

Purpose of 'Re-evaluate Workflow Rules after Field Change'


There is no connection between workflows, and there is no way to control the order of multiple workflows on the same object.  So, if you need 1 workflow to impact another one, make sure the criteria of each workflow takes that into consideration and make sure a Field Update is marked as 're-evaluate workflows'
For Example:
wf1-->type=customer  sets customerdate
wf2-->closedopp>0 and set type=customer
Since you can't control which of these WFRs runs first, you might consider setting 're-evaluate' on the 2nd Field Update to give the first WFR another chance.
NOTE:  This is a simple example to demonstrate the feature -- you would never design Workflow Rules as I have outlined them in this example.

Create records with Java script custom buttons in salesforce.


step1:
Navigate to Setup | Customize | Account | Buttons, Links and Actions
step2:
Press the New Button or Link button
step3:
Give your button a name
step4:
Choose the appropriate Display Type option but in most cases you’ll likely choose a Detail Page Button
step5:
Choose Execute JavaScript as the Behavior
step6:
In the field box you’ll add the JavaScript which I’ll explain below
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
var acct = new sforce.SObject("Account");
acct.name = 'Test Account';
acct.phone = '8147285030';
var result = sforce.connection.create([acct]);
if (result[0].getBoolean("success")) {
window.location = "/" + result[0].id + "/e";
} else {
alert('Could not create record ' + result);
}

Special Note: Dont write require script Like this
               {
              !REQUIRESCRIPT("/soap/ajax/29.0/connection.js")
               }

I hope you enjoyed this post......

Thursday 22 June 2017

                                               Test Class

Below points we should know as a developer :-
Test class must start with @isTest annotation if class class version is more than 25
Test environment support @testVisible, @testSetUp as well
To deploy to production at least 75% code coverage is required and al test case should pass .
System.debug statement are not counted as a part of apex code coverage .
@Testvisible annotaion to make visible private methods inside test classes.
@testSetup to create test records once in a method  and use in every test method in the test class .

How to write test class for both 'If 'and 'Else' statements.
public class abc
{
public integer a,b,c;
public string s;
public void maths()
{
if(s=='add')
{
  c=a+b;
}
else if(s=='sub')
{
  c=a-b;
}
}
}

@isTest
public class Testabc
{
static testMethod void testAddMethod()
{
abc obj = new abc();
obj.a = 5;
obj.b = 5;
obj.s = 'add';
obj.maths();

System.AssertEquals(obj.c,10);
}
static testMethod void testSubMethod()
{
abc obj = new abc();
obj.a = 5;
obj.b = 5;
obj.s = 'sub';
obj.maths();

System.AssertEquals(obj.c,0);
}
}

Below tips  helps us to move towards 100 % code coverage :-

1.Tips for standardcontroller

ApexPages.standradController con=ApexPages.StandradController(Needs to pass the instance of the standard/Custom Object);

2.StandardSetcontroller

ApexPages.standradSetController con=ApexPages.StandradSetController(Needs to pass the list of the standard/Custom Object);

3.For wrapper class

ClassName.WrapperclassName wrp=new ClassName.WrapperclassName();

4.Test code catch block .

We need to create a exception in test method to cover .We can do in two different ways one suppose we want an excption on update .we can do like below .

 Trick 1-

Account acc =new Account();
try{
  insert/update acc;
}catch(Exception ex){}
As mandatory fields are missing it will throw exception and it will cover the catch block .


Trick 2-We need to add two line  of code in class like below .
try{
   DML statement;
  if(Test.isRunningTest())
  Integer intTest =20/0;
 } catch(Exception qe){
 ApexPages.Message msg = new              ApexPages.Message(ApexPages.Severity.error,qe.getMessage());
  ApexPages.addMessage(msg);
 }
--------------------------------------------------------------------------------------------------------------
Good Unit Test Example:

trigger updateParent on Opportunity (after  insert) {
    // Create a Map from Account Ids to Opportunities.
    Map<Id, Opportunity> accountIdOpportunityMap = new Map<Id, Opportunity>();
   
    for(Opportunity o : Trigger.new){
        accountIdOpportunityMap.put(o.AccountId, o);
    }
   
    // Create a list of Accounts to Update.
    List<Account> accounts = new List<Account>();
   
    for(Account a : [SELECT Id, Most_Recently_Created_Opportunity_Name__c
                     FROM Account
                     WHERE Id IN :accountIdOpportunityMap.keySet()]){
                         a.Most_Recently_Created_Opportunity_Name__c =  ((Opportunity) accountIdOpportunityMap.get(a.Id)).Name;
                         accounts.add(a);
                     }
   
    update accounts;
        }

--------------------------------------------------------------------------------------------------------
Test classes:

@isTest
public class updateParent_Test {
    static testMethod void testUpdateParentAccount(){
        
        // Set up the Account record.
        Account a = new Account(Name='Test Account');
        insert a;
        
        // Verify that the initial state is as expected.
        a = [SELECT Name, Most_Recently_Created_Opportunity_Name__c 
             FROM Account 
             WHERE Id = :a.Id];
        System.assertEquals(null, a.Most_Recently_Created_Opportunity_Name__c);
        
        // Set up the Opportunity record.
        String opportunityName = 'My Opportunity';
        Opportunity o = new Opportunity(AccountId=a.Id, Name=opportunityName, 
                                        StageName='Prospecting', CloseDate=Date.today());
        
        // Cause the Trigger to execute.
        insert o;
        
        // Verify that the results are as expected.
        a = [SELECT Name, Most_Recently_Created_Opportunity_Name__c 
             FROM Account 
             WHERE Id = :a.Id];
        System.assertEquals(opportunityName, a.Most_Recently_Created_Opportunity_Name__c);
    }
    
}

   
There is a class named Test in apex which has some method which help us to write some useful test case   Test class method

Please refer below Link for  writing Test class:

http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html

Thursday 1 June 2017

Hi,
     The below code is used for  generating JSON string. To generate JSON string we have to use "JSONGenerator " and "createGenerator(true)" method. Post this code in anonymous window and click on execute.

JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartArray();
gen.writeStartObject();
gen.writenumberField('DeveloperNo.', 1);
gen.writeStringField('My Inspiration', 'Mohit');
gen.writeEndObject();
gen.writeEndArray();
String jsonString = gen.getAsString();
System.debug('jsonString:' + jsonString);
JSONParser parser = JSON.createParser(jsonString);
System.JSONToken token;
string text;
while ((token = parser.nextToken()) != null) {
system.debug('token value @@@' + token);
if ((token = parser.getCurrentToken()) != JSONToken.END_OBJECT) {
text = parser.getText();
system.debug('text value @@@' + text);
}
}

Some useful links for Understanding Json:

https://developer.salesforce.com/blogs/developer-relations/2011/09/hands-on-with-the-new-native-json-parser.html

Online Json Formater:

 https://jsonformatter.org/

Friday 28 April 2017

                 Jquery Validation In Visual force pages:


Here I'm going to explain how we can use jquery in visualforce pages.Scenario is very simple if user has to enter the name in account name field.If account name is  less than 2 character  it shows warning  message to the  user.

Whats the use of this post?
This Post shows how to embeded jquery in visualforce Pages.Use this Logic according to your requirement.

For Example:If user is filling the 'Form' (may be Website) that time you have to validate the information means you can easily achieve it using this logic

<apex:page standardcontroller="Account" showHeader="false" standardStylesheets="false">
<apex:stylesheet value="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
<apex:includeScript value="https://ajax.microsoft.com/ajax/jquery.validate/1.6/jquery.validate.min.js"/>
<apex:includeScript value="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"/>
<!-- Jquery Logic Starts here -->
<script type="text/javascript">
    $ = jQuery.noConflict();
    $(document).ready(function() {
        $('[id$=Form]').validate();          
        $('[id$=name]').rules("add",{
            required: true,
            minlength:2,
            messages:{
                required:"
<br/>Required input",
                minlength: jQuery.validator.format("
<br/>
<label style='color:red'>Please, at least 2 characters are necessary</label>"),
            }
        });  
     
     
    });
  </script>
<apex:form id="Form" >
<apex:outputlabel for="name">Account Name
<span class="star">*</span>
</apex:outputlabel>
<apex:inputtext id="name" value="{!account.name}" required="true"/>
<apex:commandButton value="Save" action="{!save}" />
</apex:form>
</apex:page>

I hope you enjoy this post..Have a great day..

Friday 21 April 2017

                                     SOQL Injection


 SOQL Injection is the breach of our application security which is dangerous for our valuable data. This happens because preventive measures are not taken into consideration when we write our SOQL queries for any DML operation.

  Let’s see  below example. I created a string variable searchstring; and used the variable in the LIKE query. This search string gets its input from the data entered by the user in the text box in the visualforce page. The searchstring passes the query string variable inside the database.query() method.
------------------------------------------------------------------------------------------------------------------

 <apex:page standardController="account" extensions="accsearchcontroller">
    <apex:form >
        <apex:inputText value="{!searchstring}" label="Input"/>
        <apex:commandButton value="Search records" action="{!search}"/>
        <apex:commandButton value="Clear records" action="{!clear}"/>
        <apex:pageBlock title="Search Result">
            <apex:pageblockTable value="{!acc}" var="a">
                <apex:column >
                    <apex:outputlink value="https://ap1.salesforce.com/{!a.id}">{!a.Name}</apex:outputlink>
                </apex:column>
                <apex:column value="{!a.id}"/>
            </apex:pageBlockTable>  
        </apex:pageBlock>
    </apex:form>
</apex:page>
 ----------------------------------------------------------------------------------------------------------
  public  class accsearchcontroller {
   public list <account> acc {get;set;}
   public string searchstring {get;set;}
   public accsearchcontroller(ApexPages.StandardController controller) {
   }
   public void search(){
     string searchquery='select name,id from account where name like \'%'+searchstring+'%\' Limit 20';
     acc= Database.query(searchquery);
   }
   public void clear(){
   acc.clear();
   }
 }
--------------------------------------------------------------------------------------------------------------
I Hope  our  code is working fine.Now we will start our discussion on SOQL Injection

Suppose if user provides this input :test%.

What will happen ?Please try it once?!!!
You got error.Suddenly you are working code shows error???!!!!

So next question??!!!

Why It throws error ? Answer is very simple  soql query dont know how to handle the user Injected data (Interesting!!!).

Then  how to resolve it ?

To prevent a SOQL injection attack, avoid using dynamic SOQL queries. Instead, use static queries and binding variables. The vulnerable example above can be re-written using static SOQL as follows:


 public  class accsearchcontroller {
   public list <account> acc {get;set;}
   public string searchstring {get;set;}
   
   public accsearchcontroller(ApexPages.StandardController controller) {
   }
   public void search(){
     acc=[select name,id from account where (IsDeleted = false and Name like :searchstring)];
 
   }
   public void clear(){
   acc.clear();
   }
 }
---------------------------------------------------------------------------------------------------------

<apex:page standardController="account" extensions="accsearchcontroller">
    <apex:form >
        <apex:inputText value="{!searchstring}" label="Input"/>
        <apex:commandButton value="Search records" action="{!search}"/>
        <apex:commandButton value="Clear records" action="{!clear}"/>
        <apex:pageBlock title="Search Result">
            <apex:pageblockTable value="{!acc}" var="a">
                <apex:column >
                    <apex:outputlink value="https://ap1.salesforce.com/{!a.id}">{!a.Name}</apex:outputlink>
                </apex:column>
                <apex:column value="{!a.id}"/>
            </apex:pageBlockTable>  
        </apex:pageBlock>
    </apex:form>
</apex:page>  

Monday 17 April 2017

How to delete all scheduler jobs at a time?


Use this code in Anonymous window 

for(CronTrigger cron :[select id from CronTrigger ])
{
  System.abortJob(cron.id);
}


After executing above code please check the  scheduled job.

How to check that?

setup-->jobs-->scheduled job 

Now question is whats cron trigger?

CornTrigger is an object in salesforce which contains schedule information for a scheduled job. It contains the CronExpression,NextFireTime,LastFireTime,status etc .
SELECT ID, CronExpression, CronJobDetail.Name, CronJobDetailId, EndTime, NextFireTime, PreviousFireTime, StartTime, State, TimesTriggered FROM CronTrigger

For Information refer below link:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm




How to find total number of records of each object in salesforce ?



Hi All,
          Sometimes we are asked to share total number of records of each object and some clients are interested to know about the storage space as well.

How to do that?
Salesforce is so smart. You can easily keep track of how many number of records are there in your organization.

 Login-->Set up-->Data Management-->Storage Usage

For your reference, I have attached screen shot below  



Thursday 26 January 2017

                       Apex REST Callouts  


HTTP and Callout Basics

REST callouts are based on HTTP. To understand how callouts work, it’s helpful to understand a few things about HTTP. Each callout request is associated with an HTTP method and an endpoint. The HTTP method indicates what type of action is desired.

Apex callouts to an external service


Get Data from a Service

1.Open the Developer Console under Your Name or the quick access menu (Setup gear icon).
2.In the Developer Console, select Debug | Open Execute Anonymous Window.
3.Delete the existing code and insert the following snippet.

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
    // Deserialize the JSON string into collections of primitive data types.
    Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    // Cast the values in the 'animals' key as a list
    List<Object> animals = (List<Object>) results.get('animals');
    System.debug('Received the following animals:');
    for (Object animal: animals) {
        System.debug(animal);
    }
}

4.Select Open Log, and then click Execute.
5. After the debug log opens, select Debug Only to view the output of the System.debug statements.
The names of the animals are displayed.


Send Data to a Service

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
// Set the body as a JSON object
request.setBody('{"name":"mighty moose"}');
HttpResponse response = http.send(request);
// Parse the JSON response
if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
} else {
    System.debug(response.getBody());
}


                                 Test Callouts:

here’s good news and bad news regarding callout testing. The bad news is that Apex test methods don’t support callouts, and tests that perform callouts fail. The good news is that the testing runtime allows you to “mock” the callout. Mock callouts allow you to specify the response to return in the test instead of actually calling the web service. You are essentially telling the runtime, “I know what this web service will return, so instead of calling it during testing, just return this data.” Using mock callouts in your tests helps ensure that you attain adequate code coverage and that no lines of code are skipped due to callouts.
Before you write your tests, let’s create a class that contains the GET and POST request examples we executed anonymously in the “Send Data to a Service” unit. These examples are slightly modified so that the requests are in methods and return values, but they’re essentially the same as the previous examples.

In the Developer Console, select File | New | Apex Class.
For the class name, enter AnimalsCallouts and then click OK.
Replace the autogenerated code with the following class definition
public class AnimalsCallouts {

    public static HttpResponse makeGetCallout() {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200) {
            // Deserializes the JSON string into collections of primitive data types.
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            // Cast the values in the 'animals' key as a list
            List<Object> animals = (List<Object>) results.get('animals');
            System.debug('Received the following animals:');
            for (Object animal: animals) {
                System.debug(animal);
            }
        }
        return response;

    }

    public static HttpResponse makePostCallout() {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setBody('{"name":"mighty moose"}');
        HttpResponse response = http.send(request);
        // Parse the JSON response
        if (response.getStatusCode() != 201) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        } else {
            System.debug(response.getBody());
        }
        return response;
    }      

}


Test a Callout with StaticResourceCalloutMock


To test your callouts, use mock callouts by either implementing an interface or using static resources. In this example, we use static resources and a mock interface later on. The static resource contains the response body to return. Again, when using a mock callout, the request isn’t sent to the endpoint. Instead, the Apex runtime knows to look up the response specified in the static resource and return it instead. The Test.setMock method informs the runtime that mock callouts are used in the test method.

Let’s see mock callouts in action. First, we create a static resource containing a JSON-formatted string to use for the GET request.

1.In the Developer Console, select File | New | Static Resource.
2.For the name, enter GetAnimalResource.
3. For the MIME type, select text/plain, even though we are using JSON.
4. Click Submit.

In the tab that opens for the resource, insert the following content. Make sure that it is all on one line and doesn’t break to the next line.

{"animals": ["pesky porcupine", "hungry hippo", "squeaky squirrel"]}

5. Press CTRL+S to save.
You’ve successfully created your static resource! Now, let’s add a test for our callout that uses this resource.

1.In the Developer Console, select File | New | Apex Class.
2.For the class name, enter AnimalsCalloutsTest and then click OK.
3.Replace the autogenerated code with the following test class definition.



@isTest
private class AnimalsCalloutsTest {

    @isTest static  void testGetCallout() {
        // Create the mock response based on a static resource
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('GetAnimalResource');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Associate the callout with a mock response
        Test.setMock(HttpCalloutMock.class, mock);
        // Call method to test
        HttpResponse result = AnimalsCallouts.makeGetCallout();
        // Verify mock response is not null
        System.assertNotEquals(null,result,
            'The callout returned a null response.');
        // Verify status code
        System.assertEquals(200,result.getStatusCode(),
          'The status code is not 200.');
        // Verify content type
        System.assertEquals('application/json;charset=UTF-8',
          result.getHeader('Content-Type'),
          'The content type value is not expected.');
        // Verify the array contains 3 items  
        Map<String, Object> results = (Map<String, Object>)
            JSON.deserializeUntyped(result.getBody());
        List<Object> animals = (List<Object>) results.get('animals');
        System.assertEquals(3, animals.size(),
          'The array should only contain 3 items.');        
    }

}


4.Press CTRL+S to save.
5.Select Test | Always Run Asynchronously. If you don’t select Always Run Asynchronously, test runs that include only one class run synchronously. You can open logs from the Tests tab only for synchronous test runs.
6.To run the test, select Test | New Run.
7.From the Test Classes list, select AnimalsCalloutsTest.
8.Click Add Selected | Run.


Test a Callout with HttpCalloutMock


To test your POST callout, we provide an implementation of the HttpCalloutMock interface. This interface enables you to specify the response that’s sent in the respond method. Your test class instructs the Apex runtime to send this fake response by calling Test.setMock again. For the first argument, pass HttpCalloutMock.class. For the second argument, pass a new instance of AnimalsHttpCalloutMock, which is your interface implementation of HttpCalloutMock. (We’ll write AnimalsHttpCalloutMock in the example after this one.)

Test.setMock(HttpCalloutMock.class, new AnimalsHttpCalloutMock());

Now add the class that implements the HttpCalloutMock interface to intercept the callout. If an HTTP callout is invoked in test context, the callout is not made. Instead, you receive the mock response that you specify in the respond method implementation in AnimalsHttpCalloutMock.

1.In the Developer Console, select File | New | Apex Class.
2.For the class name, enter AnimalsHttpCalloutMock and then click OK.
3. Replace the autogenerated code with the following class definition.


@isTest
global class AnimalsHttpCalloutMock implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
        response.setStatusCode(200);
        return response;
    }
}


4.Press CTRL+S to save.

In your test class, create the testPostCallout method to set the mock callout, as shown in the next example. The testPostCallout method calls Test.setMock, and then calls the makePostCallout method in the AnimalsCallouts class. It then verifies that the response that’s returned is what you specified in the respond method of the mock implementation.

Modify the test class AnimalsCalloutsTest to add a second test method. Click the class tab, and then add the following method before the closing bracket.

@isTest static void testPostCallout() {
    // Set mock callout class
    Test.setMock(HttpCalloutMock.class, new AnimalsHttpCalloutMock());
    // This causes a fake response to be sent
    // from the class that implements HttpCalloutMock.
    HttpResponse response = AnimalsCallouts.makePostCallout();
    // Verify that the response received contains fake values
    String contentType = response.getHeader('Content-Type');
    System.assert(contentType == 'application/json');
    String actualValue = response.getBody();
    System.debug(response.getBody());
    String expectedValue = '{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}';
    System.assertEquals(actualValue, expectedValue);
    System.assertEquals(200, response.getStatusCode());
}

5.Press CTRL+S to save.
6.Select Test | New Run.
7.From the Test Classes list, select AnimalsCalloutsTest.
8.Click Add Selected | Run.


Special Note: 

When making a callout from a method, the method waits for the external service to send back the callout response before executing subsequent lines of code. Alternatively, you can place the callout code in an asynchronous method that’s annotated with @future(callout=true) or use Queueable Apex. This way, the callout runs on a separate thread, and the execution of the calling method isn’t blocked.

When making a callout from a trigger, the callout must not block the trigger process while waiting for the response. For the trigger to be able to make a callout, the method containing the callout code must be annotated with @future(callout=true) to run in a separate thread.





                                    Apex Integration:


Apex callouts come in two flavors.

1.Web service callouts to SOAP web services use XML, and typically require a WSDL document for code generation.
2. HTTP callouts to services typically use REST with JSON.

These two types of callouts are similar in terms of sending a request to a service and receiving a response. But while WSDL-based callouts apply to SOAP Web services, HTTP callouts can be used with any HTTP service, either SOAP or REST

So you are probably asking yourself right now, “Which one should I use?” Whenever possible, use an HTTP service. These services are typically easier to interact with, require much less code, and utilize easily readable JSON. You’ll probably use SOAP mostly when integrating with legacy applications or for transactions that require a formal exchange format or stateful operations.


Authorize Endpoint Addresses:

 Before you start working with callouts, update the list of approved sites for your org on the Remote Site Settings page.

https://th-apex-http-callout.herokuapp.com
https://th-apex-soap-service.herokuapp.com


Authorize both of these endpoint URLs by following these steps.

  1. From Setup, enter Remote Site Settings in the Quick Find box, then click Remote Site Settings.
  2. Click New Remote Site.
  3. For the remote site name, enter animals_http.
  4. For the remote site URL, enter https://th-apex-http-callout.herokuapp.com. This URL authorizes all subfolders for the endpoint, like https://th-apex-http-callout.herokuapp.com/path1 and https://th-apex-http-callout.herokuapp.com/path2.
  5. For the description, enter Trailhead animal service: HTTP.
  6. Click Save & New.
  7. For the second remote site name, enter animals_soap.
  8. For the remote site URL, enter https://th-apex-soap-service.herokuapp.com.
  9. For the description, enter Trailhead animal service: SOAP.
  10. Click Save.