Thursday, 4 December 2014

How to limit the scope in batch class

While executing the batch, you can limit the scope of the batch class.

Example:

Below is the sample batch class

Batch Class:

global class BatchClass implements  Database.Batchable<Sobject>
{
                global Database.QueryLocator start(Database.BatchableContext BC){
                }
                global void execute(Database.BatchableContext BC, List<case> scope){
                }
                global void finish(Database.BatchableContext BC){
                }
}

While calling the batch class in another class

BatchClass exter = new BatchClass();
database.executebatch(exter,1);

In the execute method , we can give the parameter to limit the scope.

Tuesday, 16 September 2014

By Pass the Validation Rule while Updating record via trigger.

  For Example I have a validation rule in Opportunity Object, that we should not leave the type Field as blank. Below is the screen shot for that.

 

Validation rule for above message look like below.

 

I want to see the error message in the UI and not on trigger. If I want to update the record via trigger, I should not  see this error message.To overcome this, sometimes we want to bypass the validation rule.

To avoid validation rule for particular profile, we can give the validation rule like below.

 

we want to by pass validation rule when any Profile user attempt to execute the trigger, we can follow the below steps.

1. Create a check box field in Opportunity Object, say "By Pass Validation"

2. we need to change the validation rule like below.

3.When I change the subject of task it should update the Opportunity, Task trigger will look like below. In that trigger I have updated the opportunity field "By Pass Validation".

4. We need to create the workflow, because we have made the By Pass Validation field to true, which will always skip the validation. We want the validation to skip only the trigger.


Once the workflow is activated, It will skip the validation rule for the trigger not from UI.

Monday, 23 June 2014

TEST Class for REST API Call.

Writing TEST class for REST API

If you want to have a reference for how to write REST API, please use the below link.

http://priyamohanraj.blogspot.in/2014/05/calling-rest-api-in-salesforce.html

we should first write the MOCK Class for the http Request.

MOCK REQUEST FOR TEST CLASS

@isTest
global class Mockhttpcallouts implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req)
    {
        system.debug('------------------'+req);
        HttpResponse res = new HttpResponse();
        System.assertEquals('GET', req.getMethod());
        res.setHeader('Content-Type', 'application/json');
        res.setBody('[{"FirstName" : "test","LastName" : "data1","Email" : "test.data1@email.com","Title" : "Mr"},{"FirstName" : "test","LastName" : "data2","Email" : "test.data2@email.com","Title" : "Miss"},{"FirstName" : "test","LastName" : "data3","Email" : "test.data3@email.com","Title" : "Mr"},{"FirstName" : "test","LastName" : "data4","Email" : "test.data4@email.com","Title" : "Miss"},{"FirstName" : "test","LastName" : "data5","Email" : "test.data5@email.com","Title" : "Mr"}]');
        system.debug('------------INSIDE IF-------------');
        res.setStatusCode(200);
         
     
}
}

Now test class for the API Class

The above call will execute whenever Account record is insert, it will trigger this API call and get the contact data and insert the contact data into salesforce.

@isTest(seeAlldata =false)
public class TestExternal_APITrg
{
   @isTest static void APIClass_Test()
   {
  Account ac = new Account();
  ac.Name = 'Test Account';
  ac.CountryName__c = 'India';
  Insert ac;
  Test.startTest();
       Test.setMock(HttpCalloutMock.class, new Mockhttpcallouts());
       try
       {
        APIClass.JSONAPICall(ac);
       }
       catch (System.CalloutException e){
System.debug('ERROR:' + e);
}
}
}

Friday, 23 May 2014

Calling REST API in salesforce

Hi

Today we can see about calling REST API in salesforce.

Step 1 :

If you want to call the REST API in salesforce, first we need to add that URL into Remote Stie Settings.

Goto setup ->Administration setup ->security Controls-> Remote site settings

Click on New
Give the name and Url in the Remote site page and click on save.

Once this URL is saved, we have to write a apex class to call this REST API. Rest API will return the JSON string, below is the JSON String. below is the array of data. if you have square bracket in your JSON then it is returning the array of the data.

String jsonString = '[ {
 "FirstName" : "test",
 "LastName" : "data1",
 "Email" : "test.data1@email.com",
 "Title" : "Mr"
 },
 {
 "FirstName" : "test",
 "LastName" : "data2",
 "Email" : "test.data2@email.com",
 "Title" : "Miss"
 },
 {
 "FirstName" : "test",
 "LastName" : "data3",
 "Email" : "test.data3@email.com",
 "Title" : "Mr"
 },
 {
  "FirstName" : "test",
 "LastName" : "data4",
 "Email" : "test.data4@email.com",
 "Title" : "Miss"
 },
 {
 "FirstName" : "test",
 "LastName" : "data5",
 "Email" : "test.data5@email.com",
 "Title" : "Mr"
 } ] ';

To get this JSON, we need to send http request, to get the data via REST API.

below is the code which is used to fetch the data frm REST API

 global class APIClass
 {
   @future(callout=true)
   public static void JSONAPICall(Account ac)
   {
  Http h = new Http();
  HttpRequest req = new HttpRequest();
  req.setMethod('GET');
  string url='                                                          ';
  req.setEndpoint(url);
  HttpResponse res = h.send(req);
  JSONParser parser = JSON.createParser(res.getBody());
  list<contact> contactsdata = new List<contact>();
        JSONParser parser = JSON.createParser(jsonstr);
        while (parser.nextToken() != null)
        {
            if (parser.getCurrentToken() == JSONToken.START_ARRAY)
            {
         
                while (parser.nextToken() !=  JSONToken.END_ARRAY)
                {
                    if (parser.getCurrentToken() == JSONToken.START_OBJECT)
                    {                    
                        contact ci = new contact();
                        while (parser.nextToken() !=  JSONToken.END_OBJECT)
                        {                        
                                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText().tolowercase() == 'title'))
                                {
                                    parser.nextToken();
                                    ci.title = parser.getText();
                                }
                                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText().tolowercase() == 'firstname'))
                                {
                                    parser.nextToken();
                                    ci.firstname = parser.getText();
                                }
                                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText().tolowercase() == 'lastname'))
                                {
                                    parser.nextToken();
                                    ci.lastname = parser.getText();
                                }
                                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText().tolowercase() == 'email'))
                                {
                                    parser.nextToken();
                                    ci.email = parser.getText();
                                }
if(ac != null)
ci.AccountId = ac.Id;
                         
                        }
                        contactsdata.add(ci);
                    }
                }
            }
        }
  if(contactsdata.size() > 0)
  {
   insert contactsdata;
  }
    }

  }

In the URL you have give your API URL, and out put of the API URL is JSON Data. After fetching the data we are inserting the data into contact object.


Thursday, 24 April 2014

Encryption in salesforce

Hi

The methods in the Crypto class provide standard algorithms for creating digests, message authentication codes, and signatures, as well as encrypting and decrypting information.
These can be used for securing content in Force.com, or for integrating with external services such as Google or Amazon WebServices (AWS).

Example code for Crypto class

public class HMacAuthCallout1 {

   public void testAlexaWSForAmazon() {
      system.debug('----Checking time-----------'+timestamp);
      String action = 'salesforce Key';
      String inputStr = action;
      String algorithmName = 'SHA1';
      Blob mac = Crypto.generateDigest(algorithmName,  Blob.valueOf(inputStr));
      system.debug('-------------'+mac);
      String md5Coded = EncodingUtil.convertToHex(mac);
      system.debug('------SHA1 Code------------'+md5Coded);     
  }
}

For more information about crypto class

http://www.salesforce.com/us/developer/docs/dbcom_apex250/Content/apex_classes_restful_crypto.htm

you can check the encrypted code in

http://sha.shadecrypt.fr/SHA1-SHA256-SHA384-SHA512/encrypt.html

Thursday, 17 April 2014

System.LimitException: Apex CPU time limit exceeded

Hi

The time taken by the apex transaction in a context including validations,workflows apex code and  excluding time taken in DML,queries,callouts is called CPU time .

below is the list that will be taken into account for calculating CPU time

- All Apex code
- Library function exposed in Apex
- workflow Execution

below is the list that will not be taken into Account 

- DatabaseOperation eg: soql,DML
-  SOSL
- HTTP callouts.

If you get this error, it is because your apex code is not efficient, so follow the best practice to write the code.

like 

you can avoid so many conditions inside the for loop.
reduce the for loop.

CPU time Limits

Synchronous - 10,000 ms
Asynchronous - 60,000 ms

below are the methods where we can get the CPU time and CPU limit.

Limits.getCPUTime() - Returns the CPU time(in milliseconds) accumulated on the salesforce.com server in the current transaction.

Limits.getLimitCPUTime() - Returns the total CPU time (in milliseconds) accumulated on the salesforce.com servers in the current transaction.

Tuesday, 15 April 2014

Future Methods Limitations

Hi

Below are the list of the limitations for future annotation.

  • Methods with the future annotation must be static methods, and can only return a void type.

  • The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types. 

  • Methods with the future annotation cannot take sObjects or objects as arguments.

  • Remember that any method using the future annotation requires special consideration because the method does not necessarily execute in the same order it is called.

  • Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor.
 
  • You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a trigger from an annotated method that calls another annotated method.

  • The getContent and getContentAsPDFPageReference methods cannot be used in methods with the future annotation. 

For more information please refer the below link.

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_annotation_future.htm

Monday, 14 April 2014

MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object

Hi

 We cannot perform DML operation on setup and nonsetup Objects in salesforce.

Example for Non-setupObject -  standard object like Account,contact etc and any custom object.

Example for setObject -

Group
Group Member
Field Permission
Object Permissions
Permissionset
Permissionset Assignment
Queue sObject
SetupEntityAccess
User
UserRole
UserTerritory
Territory


If you are using a Visualforce page with a custom controller, you can only perform DML operations on a single type of sObject within a single request or action. However, you can perform DML operations on different types of sObjects in subsequent requests, for example, you can create an account with a save button, then create a user with a submit button.
You can perform DML operations on more than one type of sObject in a single class using the following process:
  1. Create a method that performs a DML operation on one type of sObject.
  2. Create a second method that uses the future annotation to manipulate a second sObject type.

For More information please refer the below link.

http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_dml_non_mix_sobjects.htm?SearchType=Stem

Friday, 11 April 2014

Salesforce to Salesforce Connection Using Trigger

Hi

When we publish connection between one org to another org, it will be very difficult for the end user to forward the data manually to the another org.

Salesforce provide some standard object, to get the connection and do some automation for connections.



PartnerNetworkConnection - It is used to get the connection Id from the salesforce.


PartnerNetworkRecordConnection - It is used to push the record into another organization.


Apex Trigger Code.

trigger ConnectionOnLead_Trg on Lead (after insert,after update) {
List<Lead> Leadlist = new List<Lead>();
for(Lead l: trigger.New)
{
    if(l.Status == 'Closed Xfer' && l.Lead_Source_Original__c == 'Prod1')
    {
        Leadlist.add(l);
    }
}
if(Leadlist.size() > 0)
{
    List<PartnerNetworkConnection> connMap = new List<PartnerNetworkConnection>();
    List<PartnerNetworkRecordConnection> connMaplist = new List<PartnerNetworkRecordConnection>();
    connMap = [select Id, ConnectionStatus, ConnectionName from PartnerNetworkConnection where ConnectionStatus = 'Accepted'];
    system.debug('---------Connection Trg----------------------'+connMap+'*****SIZE*******'+connMap.size());
    for(PartnerNetworkConnection Network : connMap)
    {
        for(Lead le : Leadlist)
        {
             PartnerNetworkRecordConnection conn= new PartnerNetworkRecordConnection();
             conn.ConnectionId = network.Id;
             conn.LocalRecordId = le.Id;
             conn.SendClosedTasks = false;
             conn.SendOpenTasks = false;
             conn.SendEmails = false;
           //  conn.ParentRecordId = newContact.AccountId);
           connMapList.add(conn);
        }
    }
    if(connMapList.size() > 0)
    {
        insert connMapList;
    }
}
}

If it met the criteria, it will automatically publish the record to another org.

Wednesday, 29 January 2014

Salesforce Code Scanner

Hi

The below URL is used to check your code Quality for your organization.

http://security.force.com/security/tools/forcecom/scanner

Tuesday, 28 January 2014

call Javascript via Apex Class


 Visualforce Page:



escape - This attribute which allows the HTML Tags and Javascripts. if we make escape = true, the character escape sequence displays as written.


Apex Class

Below is the screen shot for classes, where will have the string variable and calling the javascript on that variable.

 


Output:

when you execute the above code, the below alert box will appear.





Sunday, 19 January 2014

Add Visualforce page in Message and Alert Section of the Home Page.

Step 1:
Create a Visualforce Page.


Step 2: In the Home Page Components, click edit on Message and Alert Section

Enter the below code in that section.

Output: