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.

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

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 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 numbers of records are there in your organization.

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

For your reference, I have attached screen shot below