Thursday, 24 July 2014

Apex Email Services



Scenario:-

Email services are automated processes that use Apex classes to process the contents, headers, and attachments of inbound email.
In this Example we can create an email service that automatically creates Cases based on Case information.

Step 1:-

------

Create a New Class :- Setup -> Develop -> ApexClasses


  global class blocklist_emailhandler implements Messaging.InboundEmailHandler{

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        String myPlainText='',emailaddr='',prior='',url='',catog='',addremove='';
        myPlainText = email.plainTextBody;
        system.debug(myPlainText+'==================='+email.subject);
        // formatting the Email and storing into the variables
        if(myPlainText.contains('{') && myPlainText.contains('}')){
            string temp=myPlainText.substring(myPlainText.indexOf('{'),myPlainText.indexOf('}'));
            if(temp.contains(',')){
                for(string s:temp.split(',')){
                    if(s.contains('Email address')){
                        if(s.contains('<')){
                            emailaddr=s.substring(s.indexOf('=')+1,s.indexOf('<')-1);
                        }
                        else{
                            emailaddr=s.substring(s.indexOf('=')+1,s.length());
                        }
                    }
                    else if(s.contains('Priority')){
                        prior=s.substring(s.indexOf('=')+1,s.length());
                    }
                    else if(s.contains('URL')){
                        url=s.substring(s.indexOf('=')+1,s.length());
                    }
                    else if(s.contains('Category')){
                        catog=s.substring(s.indexOf('=')+1,s.length());
                    }
                    else if(s.contains('Add/Remove') || s.contains('Add / Remove')){
                        addremove=s.substring(s.indexOf('=')+1,s.length());
                    }
                }
            }
          //  try{
                System.Debug('**************'+emailaddr);
               //Getting Account and Contact using query
                Contact con=[Select id,Name,AccountID,Email from contact where AccountID!=null and Email!=null limit 1];
                 // Owner Should be International - Escalations Queue
                QueueSobject que= [Select Id,Queue.Id,Queue.Name from QueueSobject where Queue.Name ='International - Escalations'];
                //Creating case with the information sent by Email
                Case newcase=new Case();
                newcase.AccountID=con.AccountId;
                newcase.ContactID=con.id;
                newcase.SuppliedEmail=emailaddr;
                newcase.SuppliedName=url;
                newcase.Priority=prior;
                newcase.Type=catog;
                newcase.Add_or_Remove__c=addremove;
                newcase.Subject=email.subject;
                newcase.Status='New';
                newcase.Transfer_to__c='Support Queue';
                newcase.Ownerid=que.Queue.Id;
                insert newcase;
            //}
           // Catch(Exception e){}
        }
        return result;
    }
}

Check if there is Any Custom Fields , then you have to create those fields in your instance as well.



Step 2:-

---------

Create Email Service :- Setup -> Develop -> Email Services


Give Your Email Id in Accept Email From and Route Error Emails to this Email Addresses.
Here you have to Give the Email that from which email your sending the Emails to Sales force.

And Save


Click on New Email Address Button in Below of the Page




Enter your mail Id and Save.

Then You will get one Sales force Email Address.


Step 3:-

--------

Copy that Email Address and And You have to Send one Email the Sales force Email Address,


The Body should be in Proper below format.


Hi,

 Bla..bla..bla................

{

Email address=testemail@test.net,
Priority=High,
URL(S)=www.test2.com,
Category=Movies,
Add/Remove=Add
}


Best

bla..bla..bla..........


Here in B/W '{' and '}' the Data is Impotent. So we should maintain the constant Structure.

After Sending Email,if you can check the case object in your sales force instance.
The Case record is created with the Details of which you have sent through the mail.
The Above Task is Done..

So friends here my main intention is to people should know how to use the Email Services in Sales force.


The above information may be useful to you. 

Wednesday, 16 July 2014

Clone Button in Related List :- 


Task:-
------
The Clone button on a Account Related List of Contact, quickly creates a new contact with the same information as the existing contact, for example, when you need to add multiple contacts for the same account.

Here put a button on the related list of a Account object for the Contact to clone the selected records.

Step 1:- Create VF page and Class

<apex:page standardController="Contact" recordSetVar="record" extensions="clone_contacts" action="{!cloneprodetails}">

</apex:page>

             
 public class clone_contacts {
    Public List<Contact> Con{get;set;}
    Public Set<Id> accids=new Set<Id>();
    ApexPages.StandardSetController controller;
    public clone_contacts(ApexPages.StandardSetController controller) {
        try{           this.controller= controller;
         
           con= new List<Contact>();
           for (Contact c: (List<Contact>)Controller.getSelected()){
               accids.add(c.Id);
           }
           String dquery='Select ';
           Set<String> con_fields=Contact.SObjectType.getDescribe().fields.getMap().keySet();
           Integer temp = 1;
           for(String str:con_fields){
               dquery+=str;
               if(temp <con_fields.size()){
                   dquery+=',';
                   temp++;          
               }
           }
         
           dquery+=' from Contact where id in:accids';
           if(!accids.isempty())
               con=Database.query(dquery);
       }
       catch(Exception e){}
    }
    public PageReference cloneprodetails() {
       PageReference pageref;
       try{
           List<Contact> newRecords=new List<Contact>();
           for(Contact record:con) {
               newRecords.add(record.clone(false,true,false,false));
           }
           insert newRecords;
         
           pageref=new PageReference('/'+ApexPages.CurrentPage().getParameters().get('returl'));
       }
       Catch(Exception e){}
       return pageref;
   }

}



Step 2:- Create a List Button on Contact object , See the image






Step 3:- Add the Button into Account Related List of Contact

 Go to Account Detail Page --> Edit Layout --> Related List --> Click on Contact Properties Symbol
   

Then You get the below page , Add that Button into Selected List




Click on Ok and Save that Layout..

Then You can See the Custom Clone Button in Related List

Step 4:- Select some Records And Click on that button then you can see the cloned records




Hope the above info may helpful to you.......

Tuesday, 15 July 2014

Convert Lead Automatically Using Trigger:-

Scenario:- Convert Lead Automatically when Convert_Now__c check box is true in Lead record.

Step 1:- Create Convert_Now__c check box custom field in Lead object

Step 2:- Write a Trigger in Lead object


trigger convert_Lead on Lead (after insert,after update) {
    for(Lead led : Trigger.New){
        Lead ledold=Trigger.Isinsert?new Lead() : trigger.oldmap.get(led.id);
        if(led.Convert_Now__c!=ledold.Convert_Now__c && led.Convert_Now__c==true){
            Database.LeadConvert lc = new database.LeadConvert();
            lc.setLeadId(led.id);
            LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
            lc.setConvertedStatus(convertStatus.MasterLabel);
            Database.convertLead(lc);
        }
    }
}


The Above Trigger Converts the Lead Record when Convert_Now__c check box is true.
Wrapper class:-

How to get Object name by passing record ID:

public class KeyPrefix
{
    // map to hold global describe data
    private static Map<String,Schema.SObjectType> gd;

    // map to store objects and their prefixes
    private static Map<String, String> keyPrefixMap;

    // to hold set of all sObject prefixes
    private static Set<String> keyPrefixSet;

    private static void init() {
        // get all objects from the org
        gd = Schema.getGlobalDescribe();
    
        // to store objects and their prefixes
        keyPrefixMap = new Map<String, String>{};
    
        //get the object prefix in IDs
        keyPrefixSet = gd.keySet();
    
        // fill up the prefixes map
        for(String sObj : keyPrefixSet)
        {
            Schema.DescribeSObjectResult r =  gd.get(sObj).getDescribe();
            String tempName = r.getName();
            String tempPrefix = r.getKeyPrefix();
            keyPrefixMap.put(tempPrefix, tempName);
        }
    }

    public static String GetKeyPrefix(String ObjId)
    {
       String specialChars = '+-&|^|@() *_!$%=?.,<>{}[]|#/\\';    
        for(integer i=0; i<specialChars.split('|').size(); i++)
        ObjId= ObjId.replace(specialChars.split('|')[i], '');

        init() ;
        String tPrefix = ObjId;
        tPrefix = tPrefix.subString(0,3);
    
        //get the object type now
        String objectType = keyPrefixMap.get(tPrefix);
        return objectType;
    }
}


Call Above class from Developer console:


System.debug('::::::: '+ KeyPrefix.GetKeyPrefix('record id here') );

Use of Param Tag and Command link:-

 We have another scenario, i.e As users select the account, by clicking the name of the account, a message is displayed alerting which account was selected.

 <apex:page controller="fifthinterview">
  <apex:form >
      <apex:pageBlock title="Interview Five" id="Test">
         <apex:pageMessages > </apex:pageMessages>
     
         <apex:pageBlockTable value="{!Data}" var="acc">
            <apex:column >
                <apex:commandLink value="{!acc.name}" action="{!Calling}" reRender="Test">
                    <apex:param name="Txt" value="{!acc.id}"/>
                </apex:commandLink>
            </apex:column>
            <apex:column value="{!acc.Name}"/>
            <apex:column value="{!acc.BillingState}"/>
            <apex:column value="{!acc.Phone}"/>
            <apex:column value="{!acc.Website}"/>
          </apex:pageBlockTable>
      </apex:pageBlock>
  </apex:form>
</apex:page>


 public class fifthinterview{
    public fifthinterview(){
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,' Select an Account by Clicking its name.'));
    }
    List<Account> Varacc;
    public List<Account> getData()
    {
        string str1=Apexpages.currentpage().getParameters().get('id');
        Varacc =[Select id,Name,BillingState,Phone,Website from Account];      
        if(varacc.size()>0)
        {
            return Varacc;
        }
        return null;
    }
    public void Calling() {
        string str1=Apexpages.currentpage().getParameters().get('txt');
        Account varacc=[select id,name from Account where id=:str1];
        String ex=varacc.name;
        {
             ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,' You have Selected--> '+varacc.name+'-Organization'));
        }
    }   
}