Ajax (1) Apex Class (12) Apex Trigger (2) Community (2) Home Page (1) HTML (4) Integration (3) JS (7) KB (1) Label (1) Licenses (1) Listing (1) Log (1) OOPs (5) Sharing (1) Static Resource (1) Test Class (3) URI (1) Visualforce (10)

Monday, 3 March 2014

Bring Graphical Charts


<apex:page controller="googleChartCon" tabStyle="Account">
<apex:sectionHeader title="Accounts by Type"></apex:sectionHeader>
<apex:image url="{!chartData}"></apex:image>
</apex:page>


  --------------------------------------------
public class googleChartCon {
private String chartData;

public String getChartData()
{
return chartData;
}

public googleChartCon()
{
//obtain a list of picklist values
Schema.DescribeFieldResult F = Account.Type.getDescribe();
List<Schema.PicklistEntry> P = F.getPicklistValues();
//where chart data should be stored.
List<ChartDataItem> items = new List<ChartDataItem>();

//iterate through each picklist value and get number of accounts
// I wish we could do GROUP BY in SOQL!
for(Schema.PicklistEntry pValue : P)
{
integer Count = [select count() from Account where Type = :pValue.getValue() limit 10000];
if (Count > 0)
items.add(new ChartDataItem(pValue.getValue()+ '-['+ Count.format() + ']' , Count.format()));
}

//Prepare the chart URL
String chartPath = 'http://chart.apis.google.com/chart?chs=600x200&cht=p3';
chartData = chartPath + getChartData(items);
}

private String getChartData(List<ChartDataItem> items)
{
String chd = ''; //23,34,56
String chl = ''; //Hello|World

for(ChartDataItem citem : items)
{
chd += citem.ItemValue + ',';
chl += citem.Label + '|';
}
//remove the last comma or pipe
chd = chd.substring(0, chd.length() -1);
chl = chl.substring(0, chl.length() -1);

String result = '&chd=t:' + chd + '&chl=' + chl;
return result;
}

public class ChartDataItem
{
public String ItemValue
{
get;
set;
}

public String Label
{
get;
set;
}

public ChartDataItem(String Label, String Value)
{
this.Label = Label;
this.ItemValue = Value;
}


}

}

Pagination


  1. <apex:page controller="multiRow" tabStyle="Contact">
  2. <apex:form id="accountForm" >
  3. <apex:pageMessages />
  4. <apex:pageBlock title="Search Results" >
  5. <apex:pageBlockButtons >
  6. <apex:outputPanel rendered="{!totalPages > 1}" >
  7. <table border="0" style="width:100%; text-align: right">
  8. <tr>
  9. <td style="width:100%">&nbsp;</td>
  10. <td style="vertical-align: middle">
  11. <apex:actionStatus id="statusPaging">
  12. <apex:facet name="start">
  13. <apex:outputPanel >Please wait...</apex:outputPanel>
  14. </apex:facet>
  15. <apex:facet name="stop" />
  16. </apex:actionStatus>
  17. </td>
  18. <td style="text-align: center; white-space: nowrap">
  19. <b>Page:</b><br/>{!contactsSetController.PageNumber} of {!totalPages}
  20. </td>
  21. <td style="vertical-align: middle">
  22. <apex:commandButton value="|<" action="{!contactsSetController.First}"
  23. disabled="{!Not(contactsSetController.HasPrevious)}" rerender="accountForm" status="statusPaging"/>
  24. </td>
  25. <td style="vertical-align: middle">
  26. <apex:commandButton value="<" action="{!contactsSetController.Previous}"
  27. disabled="{!Not(contactsSetController.HasPrevious)}" rerender="accountForm" status="statusPaging"/>
  28. </td>
  29. <td style="vertical-align: middle">
  30. <apex:commandButton value=">" action="{!contactsSetController.Next}"
  31. disabled="{!Not(contactsSetController.HasNext)}" rerender="accountForm" status="statusPaging"/>
  32. </td>
  33. <td style="vertical-align: middle">
  34. <apex:commandButton value=">|" action="{!contactsSetController.Last}"
  35. disabled="{!Not(contactsSetController.HasNext)}" rerender="accountForm" status="statusPaging"/>
  36. </td>
  37. </tr>
  38. </table>
  39. </apex:outputPanel>
  40. </apex:pageBlockButtons>
  41. <apex:pageBlockTable value="{!Contacts}" var="contact" >
  42. <apex:column headerValue="Name">
  43. <apex:outputLink value="/{!contact.id}" id="contactLink">{!contact.name}</apex:outputLink>
  44. </apex:column>
  45. <apex:column value="{!contact.FirstName}"/>
  46. <apex:column value="{!contact.LastName}"/>
  47. </apex:pageBlockTable>
  48. </apex:pageBlock>
  49. </apex:form>
  50. </apex:page>
----------------------------------------------------------------------------------------------------

  1. public class multiRow {
  2. public Integer totalPages { get; set; }
  3. public ApexPages.StandardSetController contactsSetController { get; set; }
  4. public List<Contact> Contacts {
  5. get {
  6. return (List<Contact>) contactsSetController.getRecords();
  7. }
  8. }
  9.  
  10. public multiRow () {
  11. Decimal dtotalPages;
  12. Integer iRecordsPerPage = 5;
  13. Database.QueryLocator qLoc;
  14. // You can initialize the set controller using a SOQL query:
  15. qLoc = Database.getQueryLocator([Select Id, Name, AccountId, FirstName, LastName From Contact c]);
  16. contactsSetController = new ApexPages.StandardSetController(qLoc);
  17. // Or with a list of records, which is useful for SOSL searches or if you already have the records in a list.
  18. // List<Sobject> lContacts = [FIND 'smith*' IN ALL FIELDS RETURNING Contact (Id, Name, AccountId, FirstName, LastName )][0];
  19. // contactsSetController = new ApexPages.StandardSetController(lContacts);
  20. // Create the set controller
  21.  
  22. // Set the number of records to be displayed per page and calculate the number of pages.
  23. contactsSetController.setPageSize(iRecordsPerPage);
  24. dtotalPages = (contactsSetController.getResultSize() / contactsSetController.getPageSize());
  25. dtotalPages = Math.floor(dtotalPages) + ((Math.mod(contactsSetController.getResultSize(), iRecordsPerPage)>0) ? 1 : 0);
  26. totalPages = Integer.valueOf(dtotalPages);
  27. }
  28. }

Salesforce_Tips: How to Send SMS on Mobile from Salesforce

Salesforce_Tips: How to Send SMS on Mobile from Salesforce: Hi  Folks, Today I brought up a very new type of implementation in Salesforce. We integrate Communication API and Salesforce APIs . ...

Sunday, 2 March 2014

How to Unit Test Recieving Email in Apex

Suppose you have a class like this for recieving email



/**
* Email services are automated processes that use Apex classes
* to process the contents, headers, and attachments of inbound
* email.
create account from email subject
create contacts from email cc
create text and binary attachments if any

*/
global class EmailDemoReceive implements Messaging.Inboundemailhandler {

global Messaging.Inboundemailresult handleInboundemail(Messaging.Inboundemail email, Messaging.Inboundenvelope env ){
Account account;
Messaging.Inboundemailresult result = new Messaging.Inboundemailresult();
try{

if([Select count() from Account where Name =:email.subject ]==0){
account = new Account();
account.Name = email.subject;
insert account;
}else {
account=[select id from account where name=:email.subject ];
}

// Convert cc'd addresses to contacts
for (String address : email.ccAddresses) {
Contact contact = new Contact();
Matcher matcher = Pattern.compile('<.+>').matcher(address);

// Parse addresses to names and emails
if (matcher.find()) {
String[] nameParts = address.split('[ ]*<.+>')[0].replace('"', '').split('[ ]+');

contact.FirstName = nameParts.size() > 1 ? nameParts[0] : '';
contact.LastName = nameParts.size() > 1 ? nameParts[nameParts.size()-1] : nameParts[0];
contact.Email = matcher.group().replaceAll('[<>]', '');
} else {
contact.LastName = address;
contact.Email = address;
}

// Add if new
if ([select count() from Contact where Email = :contact.Email] == 0) {
contact.AccountId = account.Id;
insert contact;
}
}


for(Messaging.Inboundemail.Binaryattachment Battachment : email.binaryAttachments){
Attachment a = new attachment();
a.Name= battachment.fileName;
a.body= battachment.body;
a.parentID= account.id;
try{
insert a;}
catch(DMLException e){
system.debug(e.getMessage());
}
}

for(Messaging.Inboundemail.Textattachment tAttachment : email.textAttachments) {
Attachment a = new Attachment();
a.name= tAttachment.fileName;
a.body= blob.valueOf(tAttachment.body);
a.parentID= account.id;
insert a;
}

result.success= true;
}
catch(Exception e){
result.success=false;
result.Message='oops, failed again';

}

return result;
}

}



Unit class for testing this would be


@IsTest
private class EmailDemoReceiveHandlerTests {

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

// Set up your data if you need to

// Create the email body
email.plainTextBody = 'This should become a note';
email.fromAddress ='test@test.com';
String contactEmail = 'jsmith@salesforce.com';
email.ccAddresses = new String[] {'Jon Smith <' + contactEmail + '>'};
email.subject = 'Dummy Account Name 123';

EmailDemoReceive edr = new EmailDemoReceive();

Test.startTest();
Messaging.InboundEmailResult result = edr.handleInboundEmail(email, env);
Test.stopTest();

System.assert (result.success, 'InboundEmailResult returned a failure message');

Account [] accDb = [select ID from Account where name=:email.subject];
System.assertEquals (1, accDb.size(),'Account was not inserted');
Contact [] cDb = [select firstname,lastname from Contact where email=:contactEmail];
System.assertEquals (1, cDb.size(),'Contact was not inserted!');
Contact c = CDb[0];
System.assertEquals ('Jon', c.firstName);
System.assertEquals ('Smith', c.LastName);
Note [] nDb = [select body from Note where ParentID=:accDb[0].id];
System.assertEquals (1,nDb.size(), 'A note should have been attached');
System.assertEquals (email.plainTextBody, nDb[0].body);

}
}

Sending Email with Attachment using Apex & Visualforce page

 Public with sharing class SendemailController{     public String caseId {get;set;}     Public SendemailController(){     caseId = ApexPages.currentPage().getParameters().get(‘Id’);     }     Public Pagereference sendEmailFunction(){     Case getEmail = [SELECT Id, Contact.Email FROM Case WHERE id=:caseId];     if(getEmail.Contact.Email != null) {     String toaddress = getEmail.Contact.Email;     try {     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();     String[] toAddresses = new String[] {toaddress};     String[] ccAddresses = new String[] {‘test@gmail.com’};     mail.setToAddresses(toAddresses);     mail.setCcAddresses(ccAddresses);     mail.setReplyTo(toaddress);     mail.setSenderDisplayName(‘Name’);     mail.setSubject(‘Testing email through apex’);     mail.setBccSender(false);     mail.setUseSignature(true);     mail.setPlainTextBody(‘This is test email body. This mail is being sent from apex code’);     //mail.setHtmlBody(‘<b> This is HTML body </b>’ );     List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();     for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :caseId]){     Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();     efa.setFileName(a.Name);     efa.setBody(a.Body);     fileAttachments.add(efa);     //mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});     }     mail.setFileAttachments(fileAttachments);     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });     } catch(Exception e) {}     }     PageReference reference = new PageReference(‘http://new-developer-edition.ap1.force.com/ThankYou?caseId=’+caseId);     reference.setRedirect(true);     return reference;     }     }

Sending emails using Apex

Eassy to learn Sending emails using Apex

// Send a business proposal to each new Contact
trigger Proposal on Contact (before insert) {
// Step 0: Create a master list to hold the emails we'll send
List<Messaging.SingleEmailMessage> mails = 
new List<Messaging.SingleEmailMessage>();

for (Contact myContact : Trigger.new) {
// Step 1: Create a new Email
Messaging.SingleEmailMessage mail = 
new Messaging.SingleEmailMessage();

// Step 2: Set list of people who should get the email
List<String> sendTo = new List<String>();
sendTo.add(myContact.Email); mail.setToAddresses(sendTo);

// Step 3: Set who the email is sent from mail.setReplyTo('sirdavid@bankofnigeria.com');
mail.setSenderDisplayName('Official Bank of Nigeria');

// (Optional) Set list of people who should be CC'ed
List<String> ccTo = new List<String>();
ccTo.add('business@bankofnigeria.com'); mail.setCcAddresses(ccTo);

// Step 4. Set email contents - you can use variables! mail.setSubject('URGENT BUSINESS PROPOSAL');
String body = 'Dear ' + myContact.FirstName + ', ';
body += 'I confess this will come as a surprise to you.';
body += 'I am John Alliston CEO of the Bank of Nigeria.';
body += 'I write to request your cooperation in this ';
body += 'urgent matter as I need a foreign partner ';
body += 'in the assistance of transferring $47,110,000 ';
body += 'to a US bank account. Please respond urgently with ';
body += 'your bank account # so I may deposit these funds.'; mail.setHtmlBody(body);

// Step 5. Add your email to the master list
mails.add(mail);
}
// Step 6: Send all emails in the master list 
Messaging.sendEmail(mails);
}
 — at SaasFocus.

Salesforce @ 360 degrees: Sending Email with Attachment using Apex & Visualf...

Salesforce @ 360 degrees: Sending Email with Attachment using Apex & Visualf...: Apex Class: Public with sharing class SendemailController{ public String caseId {get;set;} Public SendemailController(){ caseId...