Sunday, 23 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


Friday, 22 August 2014

ANT SCRIPT TO TAKE DATA BACKUP FROM SALESFORCE ORGANIZATION

                To Take Data Backup by using Apache Ant

 Follow Bellow Steps : 

1. Login to Sales force Instance

2. Go To Set-up>Develop>Tools to download Force.com Migration Tool to your C:\Drive and extract it

3. Go To C:\salesforce_ant_31.0\sample\build.properties
  
   1. sf.username = xxxxxxxxxxx.com
  
   2. sf.password = xxxxxxxxxxx + secuirty Token
  
   3. sf.pkgName = your salesforce package name
  
   4. sf.serverurl = https://login.salesforce.com (If sandbox give your sales force sandbox instance)
  
   5. sf.maxPoll = 20

4. Go To C:\salesforce_ant_31.0\sample\build.xml
   
    1. If your system is in proxy then flow step one
   
        Copy this code and add at end
       
        <target name="checkproxy">
            <setproxy proxyhost="xxxxxxxxxxxxxx" proxypassword="" proxyport="xxxxxx" proxyuser=""/> (Give your proxyhost and proxyport)
        </target>
       
    2. /*Replace the retrievepkg section with the following one*/
   
        <!-- Retrieve metadata for all the packages specified under packageNames -->
        <target name="retrievePkg" depends="checkproxy">
            <mkdir dir="retrievePkg"/>
            <sf:retrieve username="${sf.username}" password="${sf.password}" serverurl="${sf.serverurl}" maxPoll="${sf.maxPoll}" retrieveTarget="retrievePkg" packageNames="${sf.pkgName}"/>
        </target>
       
5. Download Ant and Install it from http://ant.apache.org/bindownload.cgi if you do not have it (Setting up Ant_Home and Configure Path environment variable)

    a.    Download Apache Ant version 1.6 or newer to a directory of your choice: http://ant.apache.org/bindownload.cgi.
   
    b.    This directory will be known as ANT_HOME. Once the files are on your computer, there is no further installation required.
   
    c.  Add the bin directory to your path. (Only the bin and lib directories are required to run Ant.)
   
    d.    set JAVA_HOME=c:\jdk1.7.0_51
   
    e.    set PATH=%PATH%;%ANT_HOME%\bin
   
6. Copy ant-salesforce.jar and paste into your Ant installation's lib directory. The lib directory is located in the root folder of your Ant installation.

7. Run The Following Command

    open the command prompt and type
   
    C:\Users\shimran>ant -buildfile C:\salesforce_ant_31.0\sample\build.xml retrievePkg
   
    [-----------------------------------------------
    Buildfile: C:\salesforce_ant_31.0\sample\build.xml

    checkproxy:

    retrievePkg:
        [mkdir] Created dir: C:\salesforce_ant_31.0\sample\retrievePkg
    [sf:retrieve] Using proxy: web-proxy.sgp.hp.com:8080 user
    [sf:retrieve] Using proxy: web-proxy.sgp.hp.com:8080 user
    [sf:retrieve] Request for a retrieve submitted successfully.
    [sf:retrieve] Request ID for the current retrieve task: 09S90000001Hb1qEAC
    [sf:retrieve] Waiting for server to finish processing the request...
    [sf:retrieve] Request Status: InProgress
    [sf:retrieve] Request Status: Succeeded
    [sf:retrieve] Finished request 09S90000001Hb1qEAC successfully.

    BUILD SUCCESSFUL
    Total time: 1 minute 6 seconds
    -----------------------------------------------]
   
8. Now Go To Csalesforce_ant_31.0\sample\retrievePkg  (Your Back Up Data Is Here)

-----------------------------------------------------------------------------------------------------

How To Create Package In Salesforce :


1. Go To Set-up>Create>Packages>New

    a. Give your  package Name
   
    b. Language
   
2. Click Add

3. Select what data You want to take back up  and add to package

 


Friday, 11 July 2014

SALES FORCE INTEGRATION WITH JAVA (SOAP API)

  STEPS TO INTEGRATE SALES FORCE WITH JAVA

User not in proxy settings

STEP 1 : Go to (Setup/Develop/API/Generate Partner WSDL) copy all meta-data and save as                                    (Partner.wsdl)
STEP 2 : Check the version of Java like below
C:\>Java -version
Java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)
STEP 3 : Download (wsc.jar) From below Link (wsc-23.jar)
https://code.google.com/p/sfdc-wsc/downloads/list
STEP 4 : Download (partner-18.jar) From the below Link
https://code.google.com/p/sfdc-wsc/downloads/detail?name=partner-18.jar&can=2&q=
STEP 5 : Copy all files mention above on to desktop
STEP 6 : Open Command Prompt (cmd) 
C:\Users\skimran> cd desktop 
C:\Users\skimran>Desktop>java -classpath wsc-23.jar com.sforce.ws.tools.wsdlc partner.wsdl                     partner-18.jar
STEP 7 : Open Eclipse and follow the below steps
1. File | New | Java Project (Name: DemoIntegration)
2. Right click on Project | Build Path | Configure Build Path | Libraries | Add External Jar 
3. Select Desktop | wsc-23.jar and partner-18.jar | OK
4. Right click on SRC | New | Folder | (wsc)
5. Right click on wsc | New | Class | (Main)
STEP 8 : Copy below code and paste in Main Class
package wsc;
import com.sforce.soap.partner.*;  
import com.sforce.soap.partner.sobject.*;  
import com.sforce.ws.*;

public class Main {  
 public static void main(String[] args) {

ConnectorConfig config = new ConnectorConfig();
config.setUsername("USER NAME");
config.setPassword("Password + Security Token");
config.setAuthEndpoint("https://salesforce.com/services/Soap/u/18.0");

try {  
PartnerConnection connection = Connector.newConnection(config);      
System.out.println("Creating a new Account...");
SObject user = new SObject();
user.setType("User");
user.setField("LastName", "Imran");
user.setField("Email","ishaik@gmail.com");
user.setField("Username","ishaik@gmail.com");
user.setField("Alias","ishaik");
user.setField("ProfileId","00e900000013RNU");
user.setField("TimeZoneSidKey","Asia/Kolkata");
user.setField("LocaleSidKey","en_US");
user.setField("EmailEncodingKey","UTF-8");
user.setField("LanguageLocaleKey","en_US");
SaveResult[] results = connection.create(new SObject[] { user });
System.out.println("Created Account: " + results[0]);          
} catch (ConnectionException e) {
 e.printStackTrace();
}

 }

}
STEP 9 : Save and Run the program

user in proxy settings

     Just add
    
   config.setProxy("your proxy", your port);

  Ex:  config.setProxy("web-proxy.atql.seqw.com", 8080);

Tuesday, 17 June 2014

Publish Your First App with AppExchange Checkout

Getting Started


Before you begin, get to know the Force.com platform, the ecosystem, and popular use cases. There are a lot of ways to do this.DeveloperForce is a developer’s best friend. The Idea Exchange will tell you what customers are asking for. AppExchange will show you which apps are popular. The important thing is to find your niche and start building that app.
Important: AppExchange Checkout works with Managed Packages managed via a License Management Application. If you are selling a Force.com Embedded app or an API only app, contact your ISV AE for non-Checkout options.

Initial Development


Develop your great app and start showing it to people. You can get a free developer org by joining DeveloperForce. It is entirely your call how mature the app should be before showing it to prospects. In general, the earlier, the better. Early viewers and testers will validate your ideas and, more importantly, share theirs. Continue iterating on your app until it is ready for broader testing.

During this early stage of development, you will need to learn about packaging your app, so now is a good time to take a look at theISVForce Guide. Chapter 4, Packaging and Testing Your App, is a great resource. As an ISV, you will only release managed apps, so focus on that section. Keep in mind that once customers start testing your app, and once you start releasing even early versions, it can be difficult to make sweeping changes to your architecture like removing objects and fields. Also, it’s possible for you to package your app in a way that limits its distribution potential. For example, while you can package features such as workflow and record types, these are not standard features in Professional Edition and your app will not install into PE orgs. It is important for you to keep these issues in mind as you develop your app, especially if it is complex, so you can plan and manage your development, and upgrade lifecycles appropriately.


Partner With Salesforce


Signup as a Salesforce partner. This is easy and only takes a few moments. You’ll be asked a few questions and before you know it, you’ll have access to the Partner Portal. Note that your partner portal credentials will end with “@partnerforce.com.” The Partner Portal has great information in it. If you are interested in exploring the ISV program in detail, you should visit the APP Academy.




Become an AppExchange Publisher



Once you are signed up as a partner, create an AppExchange Publishing Org (APO). In the Partner Portal, you’ll see a big button at the top of the screen labeled, “Create A Test Org.” For org type, select “Partner Developer Org.” You will receive new credentials by email. Be sure to login and set your password before proceeding. Note that the system will pick a username for you. If you don’t like it, feel free to change it. The purpose of this org is to help you publish listings on AppExchange.

You are now ready to start publishing on AppExchange. Point your browser to AppExchange, scroll to the bottom of the screen, and click the “List on the AppExchange” link. Login using the APO credentials you just received. You’ll need to answer a few questions. No, you have not published on AppExchange before. Yes, you agree to the terms and conditions. You are now ready to complete your profile. Don’t worry, you can edit this at any time. Notice there’s a link at the bottom labeled “Change Partnership.” You’ll need to save your profile, then click this link. You’ll be prompted for your partnership username and a password. This should be your “@partnerforce.com” username. Be sure to click save again once your partner username and password have been accepted.
Important. AppExchange Publishing Organizations operate on a hub and spoke model. The APO is the hub. It contains all of the information about your company, but doesn't contain any information about your apps. Apps should always be developed in an org other than your APO. When you are ready to publish an app, simply click on the "Your Organizations" link, and add the developer edition where you package your app to your APO. Once you connect the orgs, you will be able see information from your spoke orgs in your hub APO org.
Congratulations, you are now ready to create a new listing. You should now be on the Publisher home screen and see a big red button with the label, “Create New Listing.” Click this. Enter your unique app name, select the “app” option, and submit. You are now on the main listing screen. Note that every field has help text to the right of it. When you run into trouble, look for the help icon in the upper right of your screen. Keep in mind that you’ll be able to edit and enhance this listing as you go.



Signup For AppExchange Checkout



Note: If your app is free, you can skip this step.
Next sign up for AppExchange Checkout, the feature that lets customers pay for your applications directly on the AppExchange. Checkout is a service from salesforce.com and Stripe that bills your customers’ credit cards automatically and deposits money into your account. Stripe provides no-touch recurring billing and subscription management, including trials, coupons, upgrades/downgrades, and automatic renewals. It also automatically updates licenses in the License Management Application (LMA).
Signing up for Checkout is very easy – no merchant bank accounts or payment gateways are required. Start on the publisher home screen. If you’re lost in AppExchange, just stop, scroll to the bottom and click the “List on the AppExchange" link.
To sign up for Checkout, click Learn About Checkout at the top of your publisher home screen. After you agree to the terms and conditions, you can create your Stripe account. Connect your checking account, authorize the AppExchange to use your new Stripe account, and you are ready to use Checkout!
To get your app ready for Checkout, first create your subscription plans in Stripe. Per month, per year, and one-time payment plans are currently supported. Go back to your publisher home screen to edit your listings and choose which plans to offer on the Pricing tab. After you select your plans and associate them with your listing, your app is ready for Checkout. Customers who buy your app on the AppExchange will be asked to provide their credit card information. If they install your app, they will be charged according to the payment details you’ve specified.



Start Your Security Review



Note: you must have a contract in place, either AppExchange Checkout, above, or ISVForce signed up with a rep, in order to start your Security Review.
Next, kick off the Security Review process. Note that all apps on AppExchange must complete the security review process successfully. Click the “Offering” tab. Select the options, “Your application is a package” and “Install it directly from the AppExchange.” Next, associate your package with your listing by clicking “Change Packages.” If you have just uploaded your package, note that it can take a few minutes before that package is visible in AppExchange. Once it is visible, it can be a few more minutes before you can associate it with a listing. Save your page before continuing. Next, click “Start Review.” You will be directed to the Security Review wizard. Here you will supply all of the necessary information to initiate your security review. Take the time to fill this out carefully – incomplete information and failed reviews mean more time until your app can go to market. After completing the form, you will be prompted for your security review payment. Enter your credit card information and your review will be submitted to our security team.


Security Review Complete



Once your security review is complete and your app has passed, you’ll want to request the ISV Business Org by logging a ticket in the Partner Portal. This is a free two-license CRM org that you can use to manage your ISV business (leads, opportunities, licenses, sales and orders) . It comes pre-installed with the License Management App (LMA). The LMA helps you control which customers are allowed to use your app, how many users they are allowed, etc. Note that AppExchange Checkout controls LMA records for any apps a customer purchases through your AppExchange listing.

If you are an API-based app, you might want to request an API token. An API token lets GE and PE customers use your API-based app (SOAP and REST only). If you are not an API-based app, you do not need to do this.
Down to the last few steps. First, revisit the listing you created above. Does it have enough screen shots? Is it easy to understand? Have you added a YouTube demo? Make your listing easy to understand and display your contact information prominently. Also, remember those beta customers? Invite them to review your app so it has some reviews before going live.



Go Live


Now the fun part. Locate your listing in the Private Listings tab. Take a deep breath. Click “Make Public.” That’s it: your listing and your app are now live.
Now the fun part begins: marketing. If you haven’t already, now is the time to get noisy. Tell the world. Post to Facebook. Post to Twitter and mention @appexchange. Post to Pinterest. And then you’ll need to repeat this process with new angles. Post when you get a good review, post when you update your package, post anything you think is newsworthy. It’s important to keep up a regular cadence of marketing activity so you can continue to help prospects get to know you.


Notes


1. This model works for ISVForce apps. However, AppExchange Checkout does not yet support OEM apps, Directory apps, or external apps. If your model is not supported, talk to your ISV AE.
2. When you sign up as a Salesforce partner, our partner team will reach out to you. You should talk to them about your app and describe your use case in detail. In some cases, you might decide you want to pursue a partnership model that does not work with this step by step guide.