Saturday 22 November 2014

BATCH APEX IN SALESFORCE



Batch as the name suggests, is used when a large data (bulk) volume is involved and it has to be redundantly processed using a particular logic.
The Batch apex, can be used to conveniently perform time to time task and some real complex job ranging from data cleansing, archiving the data to the other quality improvements.

When to use Batch Apex

The typical use of batch apex is when you want to do a bulk job, but if you do it in a regular apex you’re bound to hit the governor limits.

Batch Classes process the set of records you pass to it in batches of maximum 200 per batch.

Advantages of using Batch Apex

- Higher Governor Limits
- Can be used to process in batches
- Can be scheduled to run at different time. (read more)
- Work around to other governor limits

Here is the governor limit difference in using batch

Area                                 Normal Context                    BatchContext 
1.SOQL queries                 100 SOQL per cycle 200 SOQL per cycle 
2.records SOQL queries         50,000                           50,000,000 (getQueryLocator) 
3.code statements                   200,000                          1,000,000 (Winter '14)
4. Heap Size                             6 MB                                   12 MB 
global class ExampleBatchClass implements Database.Batchable<sObject>{
// Start Method

global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query); 

}
// Execute Logic
global void execute(Database.BatchableContext BC, List<sObject>scope){// Logic to be Executed batch wise
}
global void finish(Database.BatchableContext BC){// Logic to be Executed at finish}
}


ExampleBatchClass b = new ExampleBatchClass();
//Parameters of ExecuteBatch(context,BatchSize)
database.executebatch(b,10);


Note : if batch size is not mentioned it is 200 by default.


Note : Database.QueryLocator (If you use a QueryLocator object, the governor limit for the total number of records retrieved by SOQL queries is bypassed up to 50 million records)

ORDER OF EXECUTION IN SALESFORCE

1. The original record is loaded from the database (or initialized for an insert statement)
2. The new record field values are loaded from the request and overwrite the old values
3. All before triggers execute (TRIGGERS)
4. System validation occurs, such as verifying that all required fields have a non-null value, and running any user-defined validation rules (VALIDATIONS)
5. The record is saved to the database, but not yet committed
6. All after triggers execute
7. Assignment rules execute
8. Auto-response rules execute
9. Workflow rules execute (WORKFLOW)
10. If there are workflow field updates, the record is updated again
11. If the record was updated with workflow field updates, before and after triggers fire one more time (and only one more time)
12. Escalation rules execute
13. All DML operations are committed to the database
14. Post-commit logic executes, such as sending email

SALESFORCE CUSTOM SETTINGS


Custom settings are similar to custom objects and enable application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user.

All custom settings data is exposed in the application cache,which enables efficient access without the cost of repeated queries to the database.

This data can then be used by formula fields, validation rules, Apex, and the SOAP API.

          List Custom Settings : 

A type of custom setting that provides a reusable set of static data that can be accessed across your organization.

If you use a particular set of data frequently within your application, putting that data in a list custom setting streamlines access to it.

Data in list settings does not vary with profile or user, but is available organization-wide.
Examples of list data include two-letter state abbreviations, international dialing prefixes,
and catalog numbers for products. Because the data is cached, access is low-cost and efficient
you don't have to use SOQL queries that count against your governor limits. 
EX:

Map<String_dataset_name, CustomSettingName__c> mcs = CustomSettingName__c.getAll();
CustomSettingName__c mc = CustomSettingName__c.getValues(data_set_name);


Hierarchy Custom Settings : 

A type of custom setting that uses a built-in hierarchical logic that lets you “personalize” settings for specific profiles or users.

The hierarchy logic checks the organization, profile, and user settings for the current user and returns the most specific, or “lowest,” value.

In the hierarchy, settings for an organization are overridden by profile settings, which, in turn, are overridden by user settings. 
EX: 
CustomSettingName__c mc = CustomSettingName__c.getOrgDefaults();
CustomSettingName__c mc = CustomSettingName__c.getInstance(Profile_ID);

Monday 17 November 2014

SALESFORCE INTEGRATION WITH FACEBOOK



STEP 1 : Login To (https://developers.facebook.com/)

STEP 2 : Give your face book credentials and login

STEP 3 : Go to APP Tab (add new app)

STEP 4 : Select website and give APP Name (Click on create new Facebook App id)

STEP 4 : Under Category Section select (Apps for pages) and click (Create app id)

STEP 5 : Under (Tell us about your website) Section Site Url = Give your Visual force page url 
(https://c.ap1.visual.force.com/apex/facebookPage) and click (Next)

Note: Before going to this process create a visual force page with page name (facebookPage) and controller (FaceBookController)

VF: 
<apex:page controller="FaceBookController">
<apex:form >
<apex:commandButton value="ClickMe" action="{!fbAction}"/>
</apex:form>
</apex:page>



Controller:

public with sharing class FaceBookController {
public PageReference fbAction() {
HttpRequest req=new HttpRequest();
req.setMethod('GET');
req.setEndpoint('https://graph.facebook.com/oauth/access_token? client_id=0000000000000000
&redirect_uri=https://c.ap1.visual.force.com/apex/facebookPage
&client_secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
&code=oxoxoxoxoxoxoxoxoxoxoxoxoxo');
HttpResponse res = new HttpResponse();
http h = new Http();
res = h.send(req);

system.debug( 'Aceestoken-------'+res.getbody());
return null;
}
}


STEP 6 : Click on Finish

STEP 7 : Copy the (App Id) and (App Secret)


 



STEP 8 : Authenticate URL


https://www.facebook.com/dialog/oauth?client_id=9118292440232323219134043&redirect_uri=https://c.ap2.visual.force.com/apex/facebookPage&scope=public_profile,user_friends,email,user_about_me,user_actions.news,user_actions.video,user_birthday,user_events,user_hometown,user_likes,user_location,user_photos,user_posts,ads_management,ads_read,publish_pages,user_website,user_videos,user_tagged_places&state=hari

In the above url replace

1. client_id : with your Facebook App Id (EX: 1573492886214474)

2. redirect_uri : With your VF page url (EX: https://c.ap1.visual.force.com/apex/facebookPage )

3. state : Any string (EX: abcsdefg..)

Copy the above Authenticate URl

Open a new tab in browser paste it and click enter

It will redirect to visual force page

STEP 9 : Copy the redirect page URL and Paste in note pad

EX:

https://c.ap1.visual.force.com/apex/facebookPage?code=AQCAmhJfKJ5zSa8pYhI11qNz9L7nLEcVHz6YjiS2VUQfUJbvoIylB8DfI1M7Blwjx0jdVluatTgB_cslPf1m4mLN_PQ6ZMkcHNHpTKkiZxctic6dil_4KYpXgZv91L9cSV4t2KH7a3ZXYr3bJ2zf8U_wWEJ1_kRcdwozF7Y22ET6gH70VlnR87qaEjEEWltraO6MyEbcw7e9ChBQNLHsfJCN579lFXNmqwlhCzSmdQHCQxRWxRUNSdvMi9_jy5CGzD0hOo9MaplIbg0StUx-goGANIBz5sM0cXcyeLhc4ArU-bDL8R18zRB_O0yAmvULEq0vgBcvkG8tXOMU34SISffu&state=ShaikImran#_=_

STEP 10 : Open your controller (FaceBookController)

Replace: 
req.setEndpoint('https://graph.facebook.com/oauth/access_token? client_id=0000000000000000
&redirect_uri=https://c.ap1.visual.force.com/apex/facebookPage
&client_secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
&code=oxoxoxoxoxoxoxoxoxoxoxoxoxo');

1. client_id : Your facebook App Id

2. redirect_uri : Your visual force page url

3. client_secret : Your App Secret

4 . code : Follow step 9 and copy code which is highlighted


STEP 11 : Save it and click the button (Click me)

STEP 12 : Open the debug log and copy the acesstoken

STEP 13 : Open developer console (or) work bench

HttpRequest req=new HttpRequest();
req.setMethod('GET');
req.setEndpoint('https://graph.facebook.com/me/feed?
access_token= CAAWXFVyKF0oBAAT6
jw3zU66dZBX3e6W0zZCL07ppLyYJrSRnTb2aMP7eYAPQdtUGpp2sT
PvuX4N4Q9xlx5H2qDwSHCoDhtlTp5Y3aHvGHgZBFYqRWiaOxVQuEFTwlha574l5
8f6KPULGiSORARMPtlQCcgQGjOVd1IValQJNtvZBFf3ew9SLFbPNFVZ
Aj7B9ZCkrCGTxfXCU7xmt1plZCaE');
HttpResponse res = null;
http h= new Http();
res= h.send(req);
system.debug('resp----------'+ res.getbody());


Copy the above code and paste in your developer console or workbench

Replace security token with your security token

Executive 
Open the debug log find the resp data
NOTE :



1. The security token is time limit , ones it is expired follow the below STEPS


STEP 1: Go to STEP 8 copy the URL

Replace State = new String (EX: ddhjdhjasdhja) 
STEP 2: Follow the STEP 9 , 10 , 11, 12 , 13

2. List of End point URL

To see albums use endpoint urls
https://graph.facebook.com/albums
To see specefied albums's photo
https://graph.facebook.com/albumid/photos
To see posts
https://graph.facebook.com/me/feed

3. To insert photo in to facebook using apex code

HttpRequest req=new HttpRequest();
req.setMethod('POST);
string url ='URL=http://www.visiblebanking.com/wp-content/uploads/
2012/04/Progressive- Flo-FacebookPage-Long-Processed.png';
req.setbody(url);
req.setheader('Content-type', 'application/x-www-form-urlencoded');
req.setHeader('Content-length',string.valueof(url.length()) );
//albumid=000000000000000000
req.setEndpoint('https://graph.facebook.com/000000000000000/photos? access_token=hfsdfhshdfjksdf mdfbsjkf');
HttpResponse res = null;
http h= new Http();
res= h.send(req);

system.debug( 'Resp--------------'+res.getbody());



4 . To comment on photo 
HttpRequest req=new HttpRequest();
req.setMethod('POST);
string comment ='message=hai ra mama';
req.setbody(comment);
req.setheader('Content-type', 'application/x-www-form-urlencoded');
req.setHeader('Content-length',string.valueof(sss.length()) );
req.setEndpoint('https://graph.facebook.com/0000000000000/comments?

access_token=hfsdfhshdfjksdf mdfbsjkf');
HttpResponse res = null;
http h= new Http();
res= h.send(req);

system.debug( 'REsp----------------------'+res.getbody());


THAT'S IT FOLKS