Thursday, May 17, 2012

Force.com Summer'12 Features

There are some Awesome features coming up in Summer'12 release. This is one release for which every force.com developer is waiting. Some of the interesting features listed below. I can't wait to lay my hands on these and test them....Phew!

Apex Describe Support for Field Sets
Visualforce dynamic bindings have supported field sets for some time. In Summer ’12, Apex provides describe support
for field sets, which makes it possible to dynamically generate the SOQL necessary to load all fields in a field set. This
makes field sets easier to use in Visualforce pages that use custom controllers.
This sample uses Schema.FieldSet and Schema.FieldSetMember methods to dynamically get all the fields in the
Dimensions field set for the Merchandise custom object. The list of fields is then used to construct a SOQL query that
ensures those fields are available for display. The Visualforce page uses this class as its controller.

Single View State—Generally Available
The Single View State optimization introduced as a pilot feature in Spring ’12 is generally available in Summer ’12.
Single View State will be activated on existing organizations within 24 hours of deployment of Summer ’12 on your
Salesforce instance.

JavaScript Remoting Enhancements
We’ve enhanced JavaScript remoting in several ways.
To make it easier to work with namespaces, especially for pages that make remoting calls to methods provided in packages,
you can use the $RemoteAction global to automatically resolve the correct namespace, if any, for your remote action.
To use this facility, you must explicitly invoke JavaScript remoting. The pattern for doing this is:
Visualforce.remoting.Manager.invokeAction(
'fully_qualified_remote_action',
invocation_parameters
);

There are lot of other features like

JSON Parser
New Types 
Sorting Support for Non-Primitive Data Types in Lists
Knowledge Management Publishing Service Class
Describe Support for Field Sets
New Interfaces and Methods for Running Apex on Package Install/Upgrade and Uninstall
Allow Reparenting Option in Master-Detail Relationship Definitions
New Lookup Relationship Options etc..

You can get the release notes from here Salesforce Summer'12 Release Notes


Wednesday, May 16, 2012

Dynamic Visualforce Components Explained


Some or the other time you might have faced a challenge of dynamically generating input fields. Most of the time we sticked to dynamic HTML and embed that in our VF page to fulfil our needs.

But now, Salesforce has introduced the new Dynamic visualforce components which means you no longer will be dependent on dynamic HTML for most of your needs.

Here is a sample which shows you how to generate a dynamic input form for Account object.

Page
<apex:page standardController="Account" extensions="DynamicInputForm">
<!-- Create section header dynamically -->
<apex:dynamicComponent componentValue="{!SH}"/>
<apex:form >
<!-- Create dynamic input form for account object -->
<apex:dynamicComponent componentValue="{!ActForm}"/>
</apex:form>
</apex:page>

Class
public with sharing class DynamicInputForm
{
    public DynamicInputForm(Apexpages.standardController ctlr)
    {
        //constructor code goes here
    }

  
    //Create a page block dynamically
    public Component.Apex.PageBlock getActForm()
    {
        Component.Apex.PageBlock pb = new Component.Apex.PageBlock();
      
        //creating an input field dynamically
        Component.Apex.InputField name = new Component.Apex.InputField();
        name.expressions.value = '{!Account.Name}';
        name.id = 'name';
        Component.Apex.OutputLabel label = new Component.Apex.OutputLabel();
        label.value = 'Name';
        label.for = 'name';
        //Use the above block to create other input fields
      
        Component.Apex.CommandButton save = new Component.Apex.CommandButton();
        save.value = 'Save';
        save.expressions.action = '{!Save}';


        pb.childComponents.add(label);
        pb.childComponents.add(name);
        pb.childComponents.add(save);
        return pb;
    }

  
    //create section header dynamically
    public Component.Apex.SectionHeader getSH()
    {
        Component.Apex.SectionHeader sh = new Component.Apex.SectionHeader();
        sh.title = 'Create Account';
        return sh;
    }
}
Updated Visualforce developer guide covers this topic.

Monday, January 16, 2012

Force.com Spring'12 Release Feature Set


Apex REST Updates

We’ve streamlined Apex REST and made it even easier to develop your custom endpoint. The following changes have been made to Apex REST API:
  • Apex REST automatically provides the REST request and response in your Apex REST methods via a static RestContext object. You no longer need to declare a RestRequest or RestResponse parameter in your method.
  • User-defined types are now allowed as Apex REST parameter types.
  • Apex REST methods are now supported in managed and unmanaged packages.
  • The order of elements in the JSON or XML response data no longer has to match the Apex REST method parameter order.

Concurrent Apex Jobs

Salesforce has increased the limit for the total number of Apex classes that you can schedule concurrently to 25 (the previous limit was 10). With this higher limit, you can now schedule more Apex jobs for concurrent execution.

ContentDocument Triggers

You can now associate Apex triggers with the ContentDocument object. You can create Apex triggers for the ContentDocument object only through the Metadata API. Alternatively, you can create the triggers using the Force.com IDE or the Force.com Migration Tool, both of which make use of the Metadata API.

OFFSET added to SOQL (Pilot)
We’re adding a new clause to SOQL which will allow your app to view records after a certain offset. Use OFFSET to specify the starting row offset into the result set returned by your query.
Using OFFSET is helpful for paging into large result sets, in scenarios where you need to quickly jump to a particular subset of the entire results. For example, the following SOQL query returns a result set that skips the first 100 rows of the full query results:
SELECT Name FROM Merchandise__c WHERE Price__c > 5.0 ORDER BY Name LIMIT 50 OFFSET 100
The resulting set of records would still be limited by 50, but would begin with the 101st record in the result set.
This feature is in Developer Preview. Please contact Salesforce.com to enable it.


Sunday, August 7, 2011

How Force.com is revitalizing Application Development?

The other day I caught up with an old friend. We spent about 5 years together, working on Microsoft technologies and developing a slew of applications. Invariably, the topic veered towards technology and application development. I asked him what he was up to, and discovered that he was part of a team working on an application for a large enterprise. Some of the features read like this...

(No "ideas" were shared, these are pretty common features of all apps!)

--- Data model that supports related records
--- Large scale Business validations on forms
--- A Facebook clone for the social connect
--- Approval mechanisms, Notifications, Security, etc.

He was going on and on, so I stopped him to ask what his role in the entire exercise was and how they were planning for future versions. I learnt that he was a Lead Developer for one of the modules at one of the locations. Incidentally, the project was being worked on from four different geographies each of them sharing a significant Development piece. They were yet to come up with the first version and the project has been running for 15 months. As for the cost, your guess is better than his!

I said wow! This sounded familiar, but hang on, what are we building here? An aircraft carrier?

My heart goes out to the CIO and the end users of the application. By the time they get to realize any value out of the applications, their priorities in life would have changed. And it must have been one hell of a CFO to have approved the budget in the middle of uncertain and trying times.

OK, let's get pragmatic to understand the reason for my frustration.
(Disclaimer: I've been a fan of the Force.com platform since it's inception, and have partnered in building a Company around it, but that's after working on Microsoft technologies for many years before that, and I am still a keen follower)

Traditional Application Development follows an approach similar to this:
Code, Test, Assemble, Bundle, Deploy, Resolve, Release, Fix
This is characteristic of any technology that forces Developers to interact with libraries and have them worry about making the code work after writing it. But, as Application Development evolved in general and the way Force.com has adapted in particular, this approach has become redundant. And, here's why.

We hear it all the time - Application Developers must focus on Innovation. But, Force.com is the front runner,  if not the only technology that lets Application Developers do that. Everything else is what's called as plumbing code. So, when you do any of the following (and more), you are essentially plumbing your code.

--- Write code (or use Design mode in IDEs) for Data validations, and even common Business validations
--- Importing libraries and fretting over getting all the files in one folder to ward of the "Assembly not found" error
--- Use multiple frameworks to imitate a 3-tier architecture, making your code bulky
--- Write classes for Notifications, Messaging, Role hierarchy, etc.
--- Move from one Remote m/c to another to deploy your code before seeing your page go bust with an Invalid reference error

Sample this - how can you expect your Developer to be innovative if he is plumbing for 75% of his time?
This is exactly where Force.com wins - with Visualforce, Apex and the Force.com platform, it helps Application Developers ideate. They get a Zen like feeling. It's the holy grail of Application Development platforms.

How does Force.com achieve this? I'll cover that in detail over the next few posts, but for starters, the crux lies in how the platform provides for a combination of common feature sets bundled with an exciting user experience, and how Developers are able to leverage a Business data model with easy to build validations and formulae through clicks. As a Developer, that's making it available on a platter for me! My interest to ideate is enhanced when I look at what I already have on Force.com. There can't be a better motivation to build great apps.

I can't but mention about the social connection, and how Business and Enterprise apps have the social toolbox ready to go on Chatter.

It is not all about the plumbing though, its how you have a wonderful user experience that makes it graceful that adds all the value. There are umpteen stories of how CEOs have built up the entire environment on Force.com leaving only the code for the Developers, which is essentially about 20-25% of the entire effort.

The technology industry has been known to fade out geographical barriers, but are the IT behemoths doing it in the most efficient way for their Clients? No. 3-year, 5-year budget cycles spread over millions of dollars cannot be a sustainable approach for a technological implementation. Bordering uncertain times, CIOs must demand the best approach, the best technology and the best ROI and must leave behind the baggage of legacy brands.
In the next post, I'll write about how Force.com dilutes geographical barriers in the best possible way, thereby letting in more of the innovation in to your apps.








Tuesday, May 3, 2011

Salesforce Easy vCard

We are launching a free application on appExchange for vCard downloads from Leads, Contacts, Accounts and Users.
You can download multiple vCards as well by PDF.. Stay tuned..
Here is the appExchange URL for Easy vCard.


Thanks,
Srinivas.





Thursday, December 2, 2010

Update Namespace Prefix in Your Apex Code

As a developer, it is sometimes very tedious when we have to make all of our code as a Managed Package. Have to go to each custom field/Object in the code and change it manually with the Namespace Prefix.

I have developed a tool which takes input as your Class/VF Page/Trigger etc.. for that matter any of the file type mxml, aspx, php etc... and gives the updated output like in the screen shots below.




 'Hope this helps

You can use the tool from here.

Thanks,
Srinivas.

Monday, June 14, 2010

Our App to Chatter Developer Challenge

Sorry People,

Its been a while I have updated the blog. I am coming up with some good articles in the near future. Meantime, We have submitted a simple application to Salesforce Chatter Developer Challenge. Check this out here and vote if you like it.

http://developer.force.com/chatterdevchallenge/entry?id=087300000002lGAAAY
entry is submitted by our Technology Architect Mr Rohit Marathe

Thanks,
Srinivas
www.trekbin.com

Tuesday, May 11, 2010

Interfaces for Apex Class - Salesforce

Implementing Interfaces for Apex Classes

An interface is like a class in which none of the methods have been implemented, the method signatures are there, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface.

public class InterfaceClass
{
    //Lets consider a Bank trnasaction interface which indeed used by 3 banks BankA, BankB and BankC
    public Interface bankTransactionInterface
    {
        double deposit();
        double withdrawal();
   }
    
    //We have to implement the two methods declared in the interface for BankA
    public class BankA implements bankTransactionInterface
    {
        public double deposit()
        {
            //process the deposit
            double depositedAmount = 250;
            return depositedAmount ;
        }
        
        public double withdrawal()
        {
            //process the withdrawal
            double withdrawalAmount = 350;
            return withdrawalAmount ;
        }
       
    }
    
    //We will take another class for BankB and declare it as virtual as it is parent of BankC which has different deposit porcess but same withdrawal process as BankB.
    //For this we have to declare the deposit method as virtual and use override keyword when overriding it for BankC like showed below
    public virtual class BankB implements bankTransactionInterface
    {
        public virtual double deposit()
        {
            //process the deposit
            double depositedAmount = 450;
            return depositedAmount ;
        }
        
        public double withdrawal()
        {
            //process the withdrawal
            double withdrawalAmount = 1000;
            return withdrawalAmount ;
        }
    }
    
    public class BankC extends BankB 
    {
        public override double deposit()
        {
            //process the deposit
            double depositedAmount = 750;
            return depositedAmount ;
        }
    }
} 
'Hope this is helpful 

Thursday, May 6, 2010

Salesforce.com Customization Questions

Salesforce.com General/Customization Questions

As I am getting requests from people to post more questions on customization also. I am posting here questions in a more general way.
With this you will get a good idea on basics of salesforce.com usage.
1. Explain how MVC architechture fit for Salesforce
2. How will you create relationships between objects
3. How many types of relationships are possible on objects
4. How many data types are supported for a Custom Object Standard Field Name
5. What are activities
6. What is the difference between Task and Event
7. List and describe the features used to set permission and data access in a custom app.
8. How will you create a User
9. What are the available editions of salesforce.
10. What is the difference between Enterprise/Professional/Unlimited/force.com/Developer editions.
11. What are Sharing Settings
12. What are Person Accounts
13. How forecasting works in salesforce
14. What are the system fields. Can you name some of them
15. What are the default components available on home page?
16. How do I change the home page layout?
17. How many types of Reports I can create in salesforce. what are they
18. What is dashboard. How it is created
19. What is Page Layout
20. What is the Related List
21. What is the difference between Page Layout and Related List
22. What is mini page lay out

As I am in hurry, I will update this post with real taste of customization questions as soon as I can.

Hope this is helpful.

Thanks
Srinivas,
Technology Evangelist,
Trekbin Technologies,
www.trekbin.com

Wednesday, May 5, 2010

Visualforce Email Template with Attachment

Visualforce Email Templates with Component as Attachment

Now Email templates can be created through a visualforce. That is you can send emails to people with salesforce features.

I will explain a Visualforce email template basic/as well as with component as attachement here.

<messaging:emailTemplate recipientType="Contact" relatedToType="Account" subject="opportunity report for Account : {!relatedTo.name}">
<messaging:htmlEmailBody >
<html>
<body>
<table >
    <tr>
        <th> Name </th>
        <th> CloseDate </th>
        <th> Stage Name </th>
    </tr>
    <apex:repeat var="o" value="{!relatedTo.Opportunities}">
        <tr>
           <td>{!o.Name}</td>
           <td>{!o.CloseDate}</td>
           <td>{!o.StageName}</td>
        </tr>
    </apex:repeat>    
</table>
   
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>
The above Visualforce Template sends out all the opportunities that are related to the Contact's Account.

The one more powerful usage of Visualforce Email Template is We can introduce Custom Components in the body.

I would like to attach a PDF document which shows the number of Opporutnities for that account grouping by their close date. This I can do in a component and include that component inside my email template like this after htmlEmailBody tag.
<messaging:attachment renderAs="PDF">
    <c:opportunityGrouping accountId="{!relatedTo.Id}"/>
</messaging:attachment>
component:
<apex:component controller="opportunityGroupingController" access="global">
    <apex:attribute name="accountId" assignTo="{!accId}" type="String" description="Id of the account"/>
    <table >
            <tr>
                <th> Total </th>
                <th> CloseDate </th>
            </tr>
        <apex:repeat var="opp" value="{!GroupedOpportunites}">
            <tr>
                <td>{!opp.Total}</td>
                <td>{!opp.CloseDate}</td>
            </tr>
        </apex:repeat>    
    </table>
</apex:component>
opportunityGroupingController Class:
public class opportunityGroupingController 
{
    public String accId
    {   get;set;    }
   
    public list<AggregateResult> lstAR = new list<AggregateResult>();
   
    public list<subClass> lstSC = new list<subClass>(); 

    public class subClass
    {
        public Integer Total
        {   get;set;    }

        public date closeDate
        {   get;set;    }
       
        public subClass(AggregateResult ar)
        {
            Total = (Integer)ar.get('Total');
            closeDate = (date)ar.get('CloseDate');              
        }
    }

    public list<subClass> getGroupedOpportunites()
    {  
        lstAR = [select count(Id) Total, CloseDate from Opportunity where AccountId =:accId Group By CloseDate];
        for(Integer i = 0; i < lstAR.size(); i++)
        {
            subClass objSubClass = new subClass(lstAR[i]);
            lstSC.add(objSubClass);
        }
        return lstSC;  
    }
}

Hope this is useful.

Thanks
Srinivas
Technology Evangelist
Trekbin Technologies

Thursday, April 29, 2010

Visualforce File Upload - for Any SObject


How to Upload Attachment to any SObject using Visualforce

This article explains how you can upload file attachments to any SOobject using Visualforce.


Page:



<apex:page standardController="YourSObjectName" extensions="VFFileUpload">
  <apex:form>
      <apex:pageBlock title="Upload Attachment">
            <apex:inputFile style="width:100%" id="fileToUpload" value="{!fileBody}" filename="{!fileName}" />
            <apex:commandButton value="Upload Attachment" action="{!UploadFile}"/>
       </apex:pageBlock>
  </apex:form>
</apex:page>

Class:



public class VFFileUpload
{
    public Id recId
    {    get;set;    }
    
    public VFFileUpload(ApexPages.StandardController ctlr)
    {
       recId = ctlr.getRecord().Id;     
    }
    
    public string fileName 
    {    get;set;    }
    
    public Blob fileBody 
    {    get;set;    }
  
    public PageReference UploadFile()
    {
        PageReference pr;
        if(fileBody != null && fileName != null)
        {
          Attachment myAttachment  = new Attachment();
          myAttachment.Body = fileBody;
          myAttachment.Name = fileName;
          myAttachment.ParentId = recId;
          insert myAttachment;
           pr = new PageReference('/' + myAttachment.Id);
           pr.setRedirect(true);
           return pr;
        }
        return null;
    }    
}


You can use the above code for any object whether it is standard or custom. Happy coding!

Thanks,
Srinivas,
Technology Evangelist,
Trekbin Technologies,
www.trekbin.com

Salesforce.com FAQ - Technical Questions

Here are more technical questions, that any new one to salesforce has to learn.

1. What are recursive triggers. How can we avoid the recursion problem
2. What are Apex Governer Limits.
3. What are the Spring'10 features
4. How do you use an actionFunction tag
5. What is the difference between apex:actionFunction and apex:actionSupport tag
6. What is actionPoller
7. How do you do FileUpload using Visualforce
8. What is the difference between a Profile and Role
9. What is appexchange? How can I host my application on appexchange
10. What are the different editions available on salesforce
11. What is batch apex.
12. When will we use batch apex and what is the best practice
13. What are webservice callouts
14. What are wrapper classes
15. When do we use wrapper classes

....More questions to be followed. Stay tuned...

You will get answers for these questions mostly form apex and visualforce documentation provided by salesforce. If you find any real trouble in getting an answer I wil defintely help you out.

'Most of them I will be covering in my blog as articles in the very near future

More General/Customization questions on Salesforce.com

Thanks,
Srinivas,
Technology Evangelist,
Trekbin Technologies,
www.trekbin.com

Tuesday, April 27, 2010

Chatter or Twitter - Salesforce?


Chatter or Twitter ? :(

Salesforce has come up with another powerful (is it so?) tool called Chatter. It is a social collaboration platform where people can share anything from profile updates to documents. And of course the idea is not new. It has been taken from Twitter mainly and may be from other social networking sites like facebook.

What is the real value that chatter is going to add to your organization or sales people? your sales people can easily collaborate with each other and can track any record literally, What is happening inside the organization, what other sales reps are doing, what records are getting updated etc. This will really add a value when all the users or most of them use it extensively to track their performance against others or organizations performance. Do Sales reps really have that much time to track all of this and analyse themselves. I doubt.

Twitter is not made for professional networking and its not a performance tracking system. What i heard of from lot of tweeple (yes what they call people use twitter is tweeple :)) about why they use twitter is "No one gives a damn here on what are you doing". I really don't think this is the case with chatter.

One more biggest pain point I am seing is chatter is of no use to small scale organizations who hardly have a few sales representatives and really want to concentrate on increasing the business and not chat or tweet with other people in the orgnization.

These are all my personal opinions and What I am concerned about is, there are hell of ideas on idea exchange which have to be addressed first and these people are wasting their time on internal social networking...A surprise from salesforce.com ....... I am a big admirer of Salesforce.com and I can see the value it can bring to CRM breaking through barriers, at the same time I stick to the basics that you concentrate on increasing the business for customers and addressing their pain points. This is the first time I am getting contradictory to a salesforce.com feature.

There's plenty of comment on Twitter from folks attending Dreamforce. A sampling:
  •      "Wonder what Facebook will think of this? Could Facebook go into competition on this, providing 'private' social networks?" From @SaaSEurope, David Bradshaw.
  •      "Salesforce Chatter calling out Sharepoint 2010 - emphasizing bringing in other native apps. Also showing live tweets on SP hahaha." From @JuliaMak.
  •      "Chatter icon looks like dentures. Anyone want some Super Poligrip with that?" From @rwang0, Altimeter Group's Ray Wang.
  •      "Salesforce Dreamforce Keynote outlasts audience bladders, everyone is leaving during Benioff Chatter keynote." From @marksmithvr, Ventana Research's Mark Smith.
  •      Also from Mark Smith: "Salesforce Chatter support all Force.com native apps so that you can link collaboration across Salesforce ecosystem."
Krigsman says Chatter will need three things to succeed: ability to filter noise,accessibility to non-Salesforce customers and great performance.
reference from itbusinessedge
.

Saturday, April 24, 2010

Bulk Triggers in Salesforce


Bulk Enabled Triggers in Salesforce

When you have a need of writing a trigger, it is strongly recommended that you make it bulk enabled, so that the trigger can handle number of records whcih can be inserted/updated/deleted through data loader or any other data migration tool.
I have explained writing a basic trigger here.


I will explain how to bulk enable a trigger now in this article. Consider a scenario where you might want to update the opportunity status to "Closed-Won" depending on a boolean field CloseOpportunities__c on each of the account that has been updated (That is, if you want to close the opportunities related to accounts that are being updated). And you will be uploading hundreds of accounts using a data uploader tool.

Here is the trigger.

 


Trigger myTrigger on Account(after update)
{
   
    Set <Id> setAccId = new Set<Id>();

    for(Account a: Trigger.new)
    {
        if(a.CloseOpportunities__c)
            setAccId.add(a.Id);//set always contains distinct Ids
    }
   
    list <Opportunity> lstOpp = [select Id, StageName from Opportunity where AccountId in : setAccId];
    for(Integer i = 0; i < lstOpp.size(); i++)
    {
        lstOpp[i].StageName = "Closed-Won";
    }
    if(lstOpp.size() > 0)
        update lstOpp;

}




And a more genaralised way is something like this.


tirgger MyTrigger on SObject([your events goes here comma seperated])
{
       Set<Id> SetOfIds = new Set<Id>();

       for(SObject s : trigger.new)
       {
             SetOfIds.add(s.idField);
       }
  

       Map<Id,SObject> objMap = new Map<Id,SObject>([select Id, [Other Fields] from SObject where Id in : SetOfIds]);

       for(SObject s : trigger.new)
       {
              //do your processing with map
       }
}



 
Hope this is useful.


Thanks
Srinivas,
www.trekbin.com

Friday, April 23, 2010

Call External Web Service from Salesforce Apex

Call External Web Service from Salesforce Apex

Some times, you may need to call an extenal web service which might have written on a serverside language like .net, php or java.
Once you made your web service on the serverside or you can use a third party web service api.

I will explain you this using Authorize.net payment gateway.
There are several types of payment criterias available for Authorize.net. For an example I will go with CIM (Customer Information Manager)
You will find all the details in Authoirze.net developer documentation.

To do payments on authorize using CIM we need to create customer profile first.

Here is the apex code that calls an external web service.

//Before any Apex callout can call an external site, that site must be registered in the Remote Site Settings page, or the call will fail. The platform, by default, prevents calls to unauthorized network addresses.
//You can do this like this: got Setup->Administration setup->Security controls->Remote site settings->New and add your endpoint URL there.
//In our case the ende point is https://api.authorize.net/soap/v1/Service.asmx.

Public class callExternalWS
{
    public void invokeExternalWs()
    {
        HttpRequest req = new HttpRequest();
        //Set HTTPRequest Method
        req.setMethod('POST');
        req.setEndpoint('https://api.authorize.net/soap/v1/Service.asmx');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'text/xml; charset=utf-8');
        req.setHeader('SOAPAction', 'https://api.authorize.net/soap/v1/CreateCustomerProfile');//
        string b =   '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'+
                      '<soap:Body><CreateCustomerProfile xmlns="https://api.authorize.net/soap/v1/">'+
                      '<merchantAuthentication><name>Merchant name here</name>'+
                      '<transactionKey>Transaction Key here</transactionKey></merchantAuthentication>'+
'<profile><description>description</description>'+
                      '<email>sforce2009@gmail.com</email>'+
                      '<paymentProfiles>'+
                      '<CustomerPaymentProfileType><customerType>individual</customerType>'+
'<payment><creditCard><cardNumber>6011000000000012</cardNumber>'+
                      '<expirationDate>2009-12</expirationDate></creditCard>'+
                      '</payment></CustomerPaymentProfileType></paymentProfiles></profile>'+
                      '</CreateCustomerProfile></soap:Body></soap:Envelope>';
        req.setBody(b);
        Http http = new Http();
        try {
          //Execute web service call here       
          HTTPResponse res = http.send(req);   
          //Helpful debug messages
          System.debug(res.toString());
          System.debug('STATUS:'+res.getStatus());
          System.debug('STATUS_CODE:'+res.getStatusCode());
        //YOU CAN ALWAYS PARSE THE RESPONSE XML USING XmlStreamReader  CLASS
       } catch(System.CalloutException e) {
            //Exception handling goes here....
     }       
}
}

Hope this is useful

Saturday, April 17, 2010

How to use Batch Apex in Salesforce


Batch Apex in salesforce 
As you all might know about the salesforce governer limits on its data. When you want to fetch thousands of records or fire DML on thousands of rows on objects it is very complex in salesforce and it does not allow you to operate on more than certain number of records which satisfies the Governer limits.
But for medium to large enterprises, it is essential to manage thousands of records every day. Adding/editing/deleting them when needed.
Salesforce has come up with a powerful concept called Batch Apex. Batch Apex allows you to handle more number of records and manipulate them by using a specific syntax.
We have to create an global apex class which extends Database.Batchable Interface because of which the salesforce compiler will know, this class incorporates batch jobs. Below is a sample class which is designed to delete all the records of Account object (Lets say your organization contains more than 50 thousand records and you want to mass delete all of them).

global class deleteAccounts implements Database.Batchable
{
global final String Query;
global deleteAccounts(String q)
{
Query=q;
}

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

global void execute(Database.BatchableContext BC,List scope)
{
List <Account> lstAccount = new list<Account>();
for(Sobject s : scope)
{
 Account a = (Account)s;
lstAccount.add(a);
}
Delete lstAccount;
}

global void finish(Database.BatchableContext BC)
{
                //Send an email to the User after your batch completes
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {‘sforce2009@gmail.com’};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Batch Job is done‘);
mail.setPlainTextBody('The batch Apex job processed ');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}


///////////////////This is how the batch class is called
id batchinstanceid = database.executeBatch(new deleteAccounts(‘select Id from Account’));

When you instantiate the global class and called it using database.executeBatch, the process gets started. As you have observed the deleteAccounts class accepts your query as a parameter in the constructor and sets it to the string variable called Query.
The start method of deleteAccount class which extends database.batchable interface sets the current query to execute using the Database.getQueryLocator method.
Then the result of the query can be captured in execute method. The scope list of SObjects returned as the result of your query.
When you are executing your batch with a query which returns thousands of records, the batch will be executed with 200 records each time that is salesforce divides the total number of records in to batches. Each batch contains 200 records by default (though this is configurable less than 200 by just introducing the number when you are calling the batch class like database.executebatch(new deleteAccounts(‘your query’), number here);).
After processing each batch, the governor limits are reset.
Once the whole batch of thousands records are done the Finish method gets called and an email will be sent to the specified person.


Wednesday, April 14, 2010

Set Id for Apex insert Tag

How to set Id parameter for Apex insert Tag


I came to an interesting question on community. the above. you might want to check (reply from sforce2009, its me :) ).


Thanks,
Srinivas

Saturday, April 3, 2010

GROUP BY Clause in salesforce SOQL

How to use GROUP BY clause in Salesforce

As you know, there are some good things in Spring’10 release of salesforce.com for developers, one of them for SOQL and yet a powerful feature is Introducing GROUP BY Clause and Aggregate functions like MAX(), SUM() etc.

People who are from SQL background or who know SQL are definitely, great appreciators of GROUP BY usage in SQL.

Till now, in salesforce if we want to achieve this feature, we were dealing with the apex code only.
The new syntax is listed below.
SELECT fieldList FROM objectType[WHERE conditionExpression]
[WITH [DATA CATEGORY] filteringExpression]
[GROUP BY fieldGroupByList] | [GROUP BY ROLLUP|CUBE (fieldSubtotalGroupByList)]
[HAVING havingConditionExpression]
[ORDER BY fieldOrderByList ASC | DESC ? NULLS FIRST | LAST ?]
[LIMIT ?]
As you observe on the above syntax, GROUP BY is of 3 types here.

GROUP BY Explained with Visualforce report:

Page:

<apex:page controller="TestGroupBy">
  <apex:pageBlock title="Test Group By">
      <apex:pageBlockTable value="{!Results}" var="ar">
          <apex:column headerValue="Number of Opportunities" value="{!ar.Total}"/>
           <apex:column headerValue="Close Date" value="{!ar.CloseDate}"/>
      </apex:pageBlockTable>
  </apex:pageBlock>
</apex:page>

Class:
public class TestGroupBy
{
public list<AggregateResult> lstAR = new list<AggregateResult>();
/*
Note that any query that includes an aggregate function returns its results in an array of AggregateResult objects. AggregateResult is a read-only sObject and is only used for query results.
Aggregate functions become a more powerful tool to generate reports when you use them with a GROUP BY clause. For example, you could find the count of all opportunities for a CloseDate.

*/
public TestGroupBy()
{
lstAR = [SELECT CloseDate, COUNT(id) Total FROM Opportunity GROUP BY CloseDate];
}

public list<OppClass> getResults()
{
list<OppClass> lstResult = new list<OppClass>();
for (AggregateResult ar: lstAR)
{
oppClass objOppClass = new oppClass(ar);
lstResult.add(objOppClass);
}
return lstResult;
}

class oppClass
{
public Integer Total
{ get;set; }

public Date CloseDate
{ get;set; }

public oppClass(AggregateResult ar)
{
//Note that ar returns objects as results, so you need type conversion here
Total = (Integer)ar.get('Total');
CloseDate = (Date)ar.get('CloseDate');
}
}
}


Result:


GROUPING, GROUP BY CUBE, GROUP BY ROLLUP,

These topics are better explained in the apex pdf.
To use them in visualforce, after writing the specific query, you can use the above Page and Class

Friday, April 2, 2010

Visualforce

Visualforce is a powerful tool for designing your forms with similar look and feel of Salesforce default layouts. Let’s say you want to build a search page for Account Object. That is you wish to list all the existing accounts in a list and search functionality by using which you want to view the filtered accounts.
To do the same functionality before Visualforce era, it was very cumbersome and demand more knowledge on javascript (which may not be reliable on all browsers). Visual force is the markup language introduced by Salesforce, It provides a similar look and feel of a Salesforce standard object by just introducing some tags whose namespace is prefixed by apex.
We can use the standard object properties and styles by just setting the attribute StandardController to the desired object like below
<apex:page standardController=”Account”></apex:page>

An example which uses Account as StandardController and renders Account style is below.
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="Edit Account for{!$User.FirstName}">
<apex:pageBlockSection>
<apex:inputField value="{!account.name}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

The above code inherits a pageblock which is similar to Account standard layout page section with the Name field editable. If you observe the Pageblock’s title, we can still use the Formula Merge Fields just like in S-Controls.
In my next Article on Visualforce, I will be posting the code for the functionality described at top (Search functionality on Account listing). This will involve more abilities of Visualforce.

Triggers

Writing a basic Trigger:

The possible events of trigger are
  • before insert, before update, before delete, after insert, after update, after delete, after undelete
Example:

trigger MyTrigger on Account(after insert)
{
//Update Account Name by appending some dummy text
Account a = new Account(Id= trigger.new[0].Id);
a.Name = 'Test ' + Trigger.new[0].Name;
update a;
}

Please note, the above is a very basic trigger. I will discuss in other article how to write a Trigger which is bulk enabled