Showing posts with label Apex. Show all posts
Showing posts with label Apex. Show all posts

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.

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.








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.

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

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.