Ads

Tuesday 17 September 2013

Using static resource Dynamically in Salesforce?

Let’s suppose we have an archive in static resource with name “Contact” and you want to use this static resource on a page that displays Contact Photos dynamically. Assumption is that the images are stored with same name as product codes.
Code:

//Declare an apex variable which gets the Contact code from an apex property
<apex:variable var="contact_photo" value="{!contactPhoto}.jpg"/>
<img src="{!URLFOR($Resource.Products,contact_photo)}')" alt="" />

Email Services in Salesforce?

Email services are automated processes that use the Apex classes to process the contents, headers, and attachments of inbound email.
For example, you can create an email service that automatically creates contact records based on contact information in messages. Each email service has one or more email service addresses that can receive messages for processing.
To use the email services, click Your Name ➤ Setup ➤ Develop ➤ Email Services.
Given below email service class inserts Contact which is declare in setting of Email Services.

Class for Email Services:
global class ProcessJobApplicantEmail implements Messaging.InboundEmailHandler {

  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {

    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

    Contact contact = new Contact();
    contact.FirstName = email.fromname.substring(0,email.fromname.indexOf(' '));
    contact.LastName = email.fromname.substring(email.fromname.indexOf(' '));
    contact.Email = envelope.fromAddress;
    insert contact;

    System.debug('====> Created contact '+contact.Id);

    if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
      for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
        Attachment attachment = new Attachment();
        // attach to the newly created contact record
        attachment.ParentId = contact.Id;
        attachment.Name = email.binaryAttachments[i].filename;
        attachment.Body = email.binaryAttachments[i].body;
        insert attachment;
      }
    }
     return result;
  }
}

Test Class for Email Service:
@isTest
private class EmailTest{
static testMethod void testMe() {

  // create a new email and envelope object
  Messaging.InboundEmail email = new Messaging.InboundEmail() ;
  Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

  // setup the data for the email
  email.subject = 'Test Job Applicant';
  email.fromname = 'FirstName1 LastName1';
  env.fromAddress = 'raees.sabir@accenture.com';

  // add an attachment
  Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
  attachment.body = blob.valueOf('my attachment text');
  attachment.fileName = 'textfile.txt';
  attachment.mimeTypeSubType = 'text/plain';

  email.binaryAttachments =
    new Messaging.inboundEmail.BinaryAttachment[] { attachment };

  // call the email service class and test it with the data in the testMethod
  ProcessJobApplicantEmail emailProcess = new ProcessJobApplicantEmail();
  emailProcess.handleInboundEmail(email, env);

  // query for the contact the email service created
  Contact contact = [select id, firstName, lastName, email from contact
    where firstName = 'FirstName1' and lastName = 'LastName1'];

  System.assertEquals(contact.firstName,'FirstName1');
  System.assertEquals(contact.lastName,'LastName1');
  System.assertEquals(contact.email,'raees.sabir@accenture.com');

  // find the attachment
  Attachment a = [select name from attachment where parentId = :contact.id];

  System.assertEquals(a.name,'textfile.txt');
 }
}

How to use apex variable for total records in Visualforce?

Scenario:

 I came across a issue where visualforce does not allow one to Count or Sum records in a page.
One solution would be to add more code to the controller to do a count of the records. Which is ok.
A simple solution is to use the apex variable function in Visualforce.

Solution:
Lets do it off Contacts
In your Apex Controller : Create a SOQL query as is:
public class countcontroller{
            public List<Contact> queryResult {get;private set;}
            public String qryString {get;set;}
            public PageReference query(){
            qryString =  'SELECT Name, Email, Phone from Contact';
            queryResult = Database.query(qryString);
             return null;
       }
}

Pretty Simple and Straight Forward.
Now for the VF Page and Magic:
You will see I use the apex variable function to do a couple of things:

create a variable run the query inside that variable counting all the records by 1 within a repeat tag calling the variable with the total Kind of like a for Loop but in Visualforce instead of controller.

<apex:page standardcontroller="Contact" extensions="countcontroller">
<table width="95%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr height="5">
    <td width="35%" class="outsideround_head" align="right">
        Total Contacts Returned:&nbsp;
    </td>
    <td width="8%" class="outside_round_head_value">
        <apex:variable var="call" value="{!0}" />
        <apex:repeat var="countitall" value="{!queryResult}" >
        <apex:variable var="call" value="{!call+1}"/>
        </apex:repeat>
        <apex:outputText value="{!call}"/>
    </td>
</tr>
</table>
</apex:page>

GROUP BY - Count Method in Apex Controller?

Scenario:

We Need to do Total of Opportunities  Based on Stages. 

Thought Process:
What are the columns involved? Answer: StageName and Count or Total
What methods will we utilize to achieve these results? Answer: Group By SOQL Statement with Count.
What UI to built this neat logic? Answer: Apex Controller and VisualForce Page
Need to achieve this type of reporting for the user:


Solution:
Use Eclipse IDE or SOQL Explorer to create your SOQL Statement.
SELECT StageName, Count(Name) ce FROM Opportunity GROUP BY StageName
Second create  Apex Controller name what you like I named it TTL_Lesson, with your logic
public class TTL_Lesson{
public class OppStageHolder {
    public String OPP {get; set;}
    public Integer TTL_Opp {get; set;}
public OppStageHolder (){}
}
//Results will be placed within this List
public List queryResults{ get; set; }

//Your Page
public PageReference TTL() {

AggregateResult[] groupedResults = [SELECT StageName,
     Count(Name) ce FROM Opportunity
     GROUP BY StageName];
System.Debug('zzavg ' + groupedResults.size());
//Define your List
queryResults = new List();

for (AggregateResult ard : groupedResults)  {  
    OppStageHolder myObject = new OppStageHolder();  
    myObject.OPP = String.valueOf(ard.get('StageName'));  
    myObject.TTL_Opp = (Integer) ard.get('ce');      
    queryResults.add(myObject);  
}
return Page.TTL;
}

}

Now create your VF Page to call this and display it whenever the user clicks on this page:

<apex:page controller="TTL_Lesson" action="{!TTL}" showHeader="false" sidebar="false">
    <apex:dataTable value="{!queryResults}" var="a" id="theTable" border="2" cellpadding="1" cellspacing="1" bgcolor="#A9D0F5" >
                <apex:column >
                        <apex:facet name="header">Stage</apex:facet>
                        <apex:outputText value="{!a.OPP}"/>
                </apex:column>              
                <apex:column >
                        <apex:facet name="header">&nbsp;&nbsp;&nbsp;Count</apex:facet>
                        <apex:outputText value="{!a.TTL_Opp}"/>
                </apex:column>
    </apex:dataTable>
</apex:page>