• ankitsrivastav7771.3911494159052937E12
  • NEWBIE
  • 10 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 5
    Replies
TRIGGER-----

trigger Rfleet_DisableAttachements on Attachment(before insert,before delete,after update) {
Id devRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('RFLEET-OPP-DCVF-RT').getRecordTypeId();
Id devRecordTypeId1 = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('DC-VF Read only RT').getRecordTypeId();
if(trigger.isinsert && trigger.isbefore){
 for (Attachment att:Trigger.new){
        
            String parentObjId = att.ParentId;     //It will get profitability obj id.  
            
           list<opportunity> pid= [select Rfleet_locked__c,recordtypeid from Opportunity where Rfleet_locked__c=true ];// it get list of opp locked records.
               list<Rfleet_Profitability__c> ids=[Select Rfleet_opportunity__c from Rfleet_Profitability__c where id=:att.ParentId];
            for(Rfleet_Profitability__c pro:ids){
                for(opportunity opp:pid){    
                    if(parentObjId.startsWith('a3r') && opp.Rfleet_locked__c==true && opp.id==pro.Rfleet_opportunity__c && opp.recordtypeid==devRecordTypeId )//a3r is the starting sting in ID for all Profitability
                    {
                    att.addError('Since this opportunity was submitted for approval, you are not allowed to add a new attachment.');
                    }
                    else if(parentObjId.startsWith('a3r') && opp.Rfleet_locked__c==true && opp.id==pro.Rfleet_opportunity__c && opp.recordtypeid==devRecordTypeId1)
                    {
                    att.addError('Since this opportunity was closed, you are not allowed to add a new attachment.');
                    }
                }
            }
    }
 }
 if(trigger.isdelete && trigger.isbefore){
     for (Attachment att:Trigger.old){
      String parentObjId = att.ParentId; 
      list<opportunity> pid= [select Rfleet_locked__c,recordtypeid from Opportunity where Rfleet_locked__c=true ];// it get list of opp locked records.
               list<Rfleet_Profitability__c> ids=[Select Rfleet_opportunity__c from Rfleet_Profitability__c where id=:att.ParentId];
            for(Rfleet_Profitability__c pro:ids){
                for(opportunity opp:pid){    
                    if(parentObjId.startsWith('a3r') && opp.Rfleet_locked__c==true && opp.id==pro.Rfleet_opportunity__c && opp.recordtypeid==devRecordTypeId)//a3r is the starting sting in ID for all Profitability
                    {
                    att.addError('Since this opportunity was submitted for approval, you are not allowed to delete the attachment.');
                    }
                    else if(parentObjId.startsWith('a3r') && opp.Rfleet_locked__c==true && opp.id==pro.Rfleet_opportunity__c && opp.recordtypeid==devRecordTypeId1)
                    {
                    att.addError('Since this opportunity was closed, you are not allowed to delete the attachment.');
                    }
                }
            }
     }
 
 }
 if(trigger.isupdate && trigger.isafter){
     for (Attachment att:Trigger.new){
      String parentObjId = att.ParentId; 
      list<opportunity> pid= [select Rfleet_locked__c,recordtypeid from Opportunity where Rfleet_locked__c=true ];// it get list of opp locked records.
               list<Rfleet_Profitability__c> ids=[Select Rfleet_opportunity__c from Rfleet_Profitability__c where id=:att.ParentId];
            for(Rfleet_Profitability__c pro:ids){
                for(opportunity opp:pid){    
                    if(parentObjId.startsWith('a3r') && opp.Rfleet_locked__c==true && opp.id==pro.Rfleet_opportunity__c && opp.recordtypeid==devRecordTypeId)//a3r is the starting sting in ID for all Profitability
                    {
                    att.addError('Since this opportunity was submitted for approval, you are not allowed to update the attachment.');
                    }
                    else if(parentObjId.startsWith('a3r') && opp.Rfleet_locked__c==true && opp.id==pro.Rfleet_opportunity__c && opp.recordtypeid==devRecordTypeId1)
                    {
                    att.addError('Since this opportunity was closed, you are not allowed to update the attachment.');
                    }
                }
            }
     }
 
 }
 }


@testclass

@isTest(SeeAllData=true)
    public class Rfleet_DisableAttachements_Test {
    static testMethod void  Rfleet_DisableAttachements(){
    

    Id devRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('RFLEET-OPP-DCVF-RT').getRecordTypeId();
    Id devRecordTypeId1 = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('DC-VF Read only RT').getRecordTypeId();
    //RecordType rt = [select Id from RecordType where Name = 'RFLEET-OPP-DCVF-RT' and SobjectType = 'opportunity' LIMIT 1];
    Opportunity opp=new Opportunity();
    //opp.RecordTypeId = rt.id; 
    opp.RecordTypeId=devRecordTypeId ;
    opp.Rfleet_locked__c = True;
    
    opp.name='fdf';
    //opp.id='a3rm0000000D6Z5';
    //opp.id==pro.Rfleet_opportunity__c
    
    opp.stagename='Internal Approbation';
    opp.closedate=System.Today();
    insert opp;
    opp.stagename='Proposal to Customer';
    update opp;

    Attachment attach=new Attachment();
     //attach.id=opp.Id;
    attach.Name='TestAtt'; 
    Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body'); 
    attach.body=bodyBlob; 
    attach.parentId=opp.Id; 
    insert attach; 
    
    Rfleet_Profitability__c Pro=new Rfleet_Profitability__c();
    pro.Rfleet_opportunity__c=opp.Id;
    //pro.id=attach.id;
    
  // pro.id='a3rm0000000D6Z5';
  
           try{
          insert pro;

              }catch (DMLException e) {} 

    List<Attachment> attachments=[select id, name from Attachment where parent.id=:opp.id ];
    System.assertEquals(1, attachments.size());
     attach = [SELECT Id, name from Attachment where parent.id=:opp.id];
     //System.assertEquals(pro.Id, attach.ParentId);
     update attach;
     delete attach;  

         }
         }
Hi i am just new to  salesforce can anyone help . i would like to write a trigger which update response time on response__c field (custom date/time field ) when a mail is semd from case..
controller# 


public class FileUploader {
    public string nameFile {
        get;
        set;
    }
    public Blob contentFile {
        get;
        set;
    }
     
      public List < String > FieldsInFile {
        get;
        set;
    }
    
    String[] filelines = new String[] {};
    List < ccs > ccsupload;
    
       public Pagereference ReadFile() {
        
         
        if(contentFile==Null)
        {
           ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Invalid template or file while processing your records...!');
            ApexPages.addMessage(errormsg);
        }
        else
        {
        FieldsInFile = new List < String > ();
        nameFile = contentFile.toString();
        filelines = nameFile.split('\n');
        ccsupload = new List < ccs > ();
        //List<String> FirstLine = new List<String>();
        //FirstLine = filelines[0].split(,);
        Set < String > ObjectFieldList = new Set < String > ();
        for (String FName: schema.sobjecttype.ccs.fields.getmap().keyset()) {
            ObjectFieldList.add(FName.RemoveEnd('__c'));
        }
        if (!filelines.isEmpty()) {
            FieldsInFile = filelines[0].toLowerCase().trim().split(',');
            if (FieldsInFile.isEmpty()) {
               ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'No fields present in the file...!');
            ApexPages.addMessage(errormsg);
                //Exception : No fields present in the file
                return null;
            }
            System.debug('**********************************' + ObjectFieldList.containsall(FieldsInFile));
            System.debug('**********************************' + schema.sobjecttype.ccs.fields.getmap().keyset().containsall(FieldsInFile));
            if (!(ObjectFieldList.containsall(FieldsInFile) || schema.sobjecttype.ccs.fields.getmap().keyset().containsall(FieldsInFile))) {
                //Exception : Fields in File not correct - Please check spelling
                return null;
            }
        }
        for (Integer i = 1; i < filelines.size(); i++) {
            ccs a = new ccs();
            List < String > inputvalues = new List < String > ();
            inputvalues = filelines[i].split(',');

            for (Integer j = 0; j < FieldsInFile.size(); j++) {
                if (FieldsInFile.get(j) == 'Service__c')

                    a.Type_of_Service__c = inputvalues[j];

                if (FieldsInFile.get(j) == 'First_Name__c')

                    a.Member_First_Name__c = inputvalues[j];

                if (FieldsInFile.get(j) == 'Street__c')

                    a.Street__c = inputvalues[j];

                if (FieldsInFile.get(j) == 'City__c')

                    a.City__c = inputvalues[j];

                if (FieldsInFile.get(j) == 'PO__c')

                    a.PO__c = inputvalues[j];


            }


            ccsupload.add(a);
        }
       
        //try{
        insert ccsupload;
        //}
        /*catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
            ApexPages.addMessage(errormsg);
        }*/
        }
        return null;
    }
    
 
    
    
    public List < ccs > getuploadedccs() {
        if (ccsupload != NULL)
            if (ccsupload.size() > 0)
                return ccsupload;
            else
                return null;
        else
            return null;
    }
    
      


}



page#

<apex:page sidebar="false" controller="FileUploader">

    

<style>
    .headerRow {
background:#D0D0D0!important ;

</style>

    <apex:form >
        <apex:sectionHeader title="Upload data" />
        <apex:pagemessages />
        <apex:pageBlock >
            <center>
                <apex:inputFile value="{!contentFile}" filename="{!nameFile}" />
                <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;" />
                <apex:commandButton action="{!refresh}" value="Reset" id="Button" style="width:70px;" />

                <br/>
                <br/> <font color="red"> <b>Note: Please use the standard CSV template to upload Data.  </b> </font>
            </center>

            <apex:pageblocktable value="{!getuploadedccs}" var="acc" rendered="{!NOT(ISNULL(getuploadedccs))}" style="background-color:#00FFFF;">

               
                <apex:column headerValue="Record id" width="30%" style="background-color:#00FFFF;">
                    <apex:outputField value="{!acc.Id}"  />
                   <a href="/{!acc.Id}" id="{!acc.Id}" target="_blank" location="top" fullscreen="no" onblur="LookupHoverDetail.getHover('{!acc.Id}').hide();"
                                onfocus="LookupHoverDetail.getHover('{!Acc.Id}', '/{!Acc.Id}/m?retURL=%2F{!Acc.Id}&isAjaxRequest=1').show();"
                                
                                onmouseout="LookupHoverDetail.getHover('{!acc.Id}').hide();"
                                 
                                onmouseover="LookupHoverDetail.getHover('{!acc.Id}', '/{!acc.Id}/m?retURL=%2F{!acc.Id}&isAjaxRequest=1').show();">View</a><br/>
                                
                  <a href="/{!acc.Id}/e?retURL=%2F{!Acc.Id}" id="{!acc.Id}" target="_blank" location="top" fullscreen="no" onblur="LookupHoverDetail.getHover('{!acc.Id}').hide();">Edit</a><br/>  
                              
                  
                </apex:column>               
                <apex:column headerValue="Member First Name" width="30%" style="background-color:#00FFFF;">
                    <apex:outputField value="{!acc.First_Name__c}" />
                </apex:column>
                
                <apex:column headerValue="Type of Service" style="background-color:#00FFFF;">
                    <apex:outputField value="{!acc.Service__c}" />
                </apex:column>
                
                <apex:column headerValue="Street" style="background-color:#00FFFF;">
                    <apex:outputField value="{!acc.Street__c}" />
                </apex:column>
                <apex:column headerValue="City" style="background-color:#00FFFF;">
                    <apex:outputField value="{!acc.City__c}" />
                </apex:column>
                <apex:column headerValue="PO" style="background-color:#00FFFF;">
                    <apex:outputField value="{!acc.PO__c}" />
                </apex:column>

                
   

            </apex:pageblocktable>
            

        </apex:pageBlock>
    </apex:form>
</apex:page>
trigger AccountDuplicatePreventer on Account(before insert,before update)
{
    Set<String> vSetNewPersonEmail = new Set<String>();
    Map<String, Account> OldAccounttMap = new Map<String, Account>();
    Map<String, Account> NewAccountMap = new Map<String, Account>();
   
    for(Account a: trigger.new){
   
        NewAccountMap.put(a.PersonEmail,a);
    }
    List<Account> vLstOldAccount = [SELECT Id,name,PersonEmail FROM Account WHERE isPersonAccount = true AND PersonEmail in: NewAccountMap.keyset() ];
    system.debug('this is test'+vLstOldAccount );
    If(vLstOldAccount.size()>0){
       
    for(Account b: vLstOldAccount){
        OldAccounttMap.put(b.PersonEmail,b);
    }
    for(Account a: trigger.new){
  
           a.PersonEmail.adderror('There is already another Account with the same PersonEmail.' +
                'Refer: <a href=\'/' +
                OldAccounttMap.get(a.PersonEmail) + '\'>' +
                OldAccounttMap.get(a.PersonEmail).Name + '</a>',
                FALSE
            );

 
}
}


Test Class

@isTest(SeeAllData=True)
Public Class TestcontactDuplicatePreventer
{
Static testMethod Void contactDuplicatePreventer()
{
   Account ac= new Account();
   ac.LastName='xyz';
   ac.Email__c='test@sales.com';
   ac.PersonEmail='test@ibm.com';
}
}
Controller class:
public with sharing class AccountPageSearchController
{
    public String SearchField1{get;set;}
    public String SearchField2{get;set;}
    public String SearchField3{get;set;}
    public String SearchField4{get;set;}
    public Boolean CreateNewAccount{get;set;}
    public List<Account> AccountResult{get;set;}
    public String ContractQueryString{get;set;}
    public String AccountQueryString{get;set;}
    //public RecordType RTID;
    public string RecordType;
  
    public AccountPageSearchController(ApexPages.StandardController controller)
    {
        CreateNewAccount = false;
        AccountResult = new List<Account>();
        SearchField1='';
        SearchField2='';
        SearchField3='';
        SearchField4='';
    }
   
public list<selectOption> getRecordTypes{
    get{
    if(getRecordTypes == null)
    {

             String selectedRecordType ;
            getRecordTypes = new list<selectOption>();
            Schema.DescribeSObjectResult d = Schema.SObjectType.Account;
            Map<Id,Schema.RecordTypeInfo> rtMapById = d.getRecordTypeInfosById();
            for(RecordType rt:[SELECT Id,Name FROM RecordType WHERE SobjectType='Account'])
            {
            Schema.RecordTypeInfo rtInfo =  rtMapById.get(rt.id);
            if(rtInfo.isAvailable())
            {
            getRecordTypes.add(new selectOption(rtInfo.getRecordTypeId(),rtInfo.getName()));
             if(rtInfo.isDefaultRecordTypeMapping())
             {
             selectedRecordType = rtInfo.getRecordTypeId();
             }
                }
            }
        }
             return getRecordTypes;
    }
    private set;
    }

    public pagereference searchit()
    {
        AccountQueryString='Select id,name,(select id,name,StageName from opportunities) from account where';
        String ContractQueryString='Select id,name,AccountId from contact where';
        String IdString='';
        List<id> AccId = new List<id>();
        if(SearchField2!='' && SearchField2!=null && SearchField2.length() >2)
            ContractQueryString += ' name LIKE \''+ SearchField2 +'%\'' +' and';
        if(SearchField3!='' && SearchField3!=null && SearchField3.length() >2)
            ContractQueryString += ' email = \''+ SearchField3 +'\' and';
        if(SearchField4!='' && SearchField4!=null && SearchField4.length() >2)
            ContractQueryString += ' phone= \''+ SearchField4 +'\'';
        else
            ContractQueryString=ContractQueryString.removeend(' and');
        if(SearchField1 != '' && SearchField1 != null)
            AccountQueryString += ' name LIKE \''+SearchField1+'%\'' +' and';
        system.debug('################'+ContractQueryString);
        if(SearchField2!='' || SearchField3!='' || SearchField4!='')
        {
            for(Contact Ctemp: database.query(ContractQueryString))
            {
                AccId.add(Ctemp.AccountId);
        
            }
            if(!AccId.isEmpty())
            {
                for(String Aid :AccId)
                    if(Aid !=null)
                        IdString += '\''+Aid+'\',';
                    else
                        continue;
                if(IdString == '' )
                    IdString ='\'\'';
            }
            else
                IdString ='\'\'';
            IdString = IdString.removeend(',');
                AccountQueryString +=  ' id IN('+IdString+')';
           
        }
        else if(SearchField1 == '' || SearchField1 == null)
            return null;
        else
            AccountQueryString = AccountQueryString.removeend(' and');
        System.debug(ContractQueryString+'***************'+AccountQueryString);
       
        System.debug('***************'+AccountQueryString);
        AccountResult = new List<Account>((List<Account>)database.query(AccountQueryString));
        if(AccountResult.isEmpty())
            CreateNewAccount=true;
        else
            CreateNewAccount=false;
        return null;
    }

}

Vf Page:

<apex:page standardController="Account" extensions="AccountPageSearchController" >
    <apex:outputPanel >
        <apex:form >
            <apex:pageBlock >
               
                Account Name  <apex:inputText value="{!SearchField1}"  />
                Contact Name  <apex:inputText value="{!SearchField2}" />
                Contact Email  <apex:inputText value="{!SearchField3}" />
                Contact Number  <apex:inputText value="{!SearchField4}" />
                {!ContractQueryString}
                <apex:commandButton value="Search" action="{!searchit}"/>
            </apex:pageBlock>
            <apex:pageBlock rendered="{!IF(AccountResult.size > 0,true,false)}" >
                <apex:pageBlockTable var="Acc" value="{!AccountResult}">
                    <apex:column width="10%">
                        <apex:outputLink value="/{!Acc.id}/e?retURL={!Acc.id}">Edit</apex:outputLink>
                    </apex:column>
                    <apex:column value="{!Acc.Name}" width="30%" />
                    <apex:column >

                    <apex:pageBlockTable var="Opp" value="{!Acc.Opportunities}" rendered="{!IF(Acc.Opportunities.size >0,true,false)}">
                        <apex:column width="10%">
                            <apex:outputLink value="/{!Opp.id}/e?retURL={!Opp.id}">Edit</apex:outputLink>
                        </apex:column>
                        <apex:column value="{!Opp.Name}"/>
                    </apex:pageBlockTable>
                    <apex:outputLink value="/setup/ui/recordtypeselect.jsp?ent=Opportunity&retURL=/apex/SOSL&save_new_url=%2F006%2Fe%3FretURL%3D%252F006%252Fo" rendered="{!IF(Acc.Opportunities.size == 0,true,false)}">Create Opportunity</apex:outputLink>
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlock>
            <apex:pageBlock rendered="{!CreateNewAccount}" >
                <apex:pageBlockSection >
                    <apex:inputField value="{!Account.Name}"/>
                    <apex:inputField value="{!Account.Business_Type__c}"/>
                    <apex:inputField value="{!Account.Email__c}"/>
                   
                </apex:pageBlockSection>
                <apex:pageBlockButtons >
                        <apex:commandButton value="Save" action="{!Save}"/>
                    </apex:pageBlockButtons>
            </apex:pageBlock>
        </apex:form>
    </apex:outputPanel>
</apex:page>
@isTest(SeeAllData=true)
public class TestupdateFallout
{
static testMethod  void updateFallout()
{
  Messaging.InboundEmail email = new Messaging.InboundEmail() ;
  Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
  // setup the data for the email

  email.fromAddress = 'rajat@salesforce.com';

  env.toAddress=('test_email_service@v-owqjewyhqhs8stb49ok48inl50drvv20gd0siiwzsbiu38uix.11-4ypueay.cs18.apex.salesforce.com');
 
  email.htmlBody='<?xml version="1.0" encoding="UTF-8"?><ValidateConfigResult><Configuration><ConfigId>CE05502807</ConfigId><Status>false</Status></Configuration></ValidateConfigResult>';
  
  test.startTest();
   
  updateFallout testInbound=new updateFallout();
 
   testInbound.handleInboundEmail(email,env);
      
     test.stopTest();
         

}   
}
TRIGGER-----

trigger Rfleet_DisableAttachements on Attachment(before insert,before delete,after update) {
Id devRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('RFLEET-OPP-DCVF-RT').getRecordTypeId();
Id devRecordTypeId1 = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('DC-VF Read only RT').getRecordTypeId();
if(trigger.isinsert && trigger.isbefore){
 for (Attachment att:Trigger.new){
        
            String parentObjId = att.ParentId;     //It will get profitability obj id.  
            
           list<opportunity> pid= [select Rfleet_locked__c,recordtypeid from Opportunity where Rfleet_locked__c=true ];// it get list of opp locked records.
               list<Rfleet_Profitability__c> ids=[Select Rfleet_opportunity__c from Rfleet_Profitability__c where id=:att.ParentId];
            for(Rfleet_Profitability__c pro:ids){
                for(opportunity opp:pid){    
                    if(parentObjId.startsWith('a3r') && opp.Rfleet_locked__c==true && opp.id==pro.Rfleet_opportunity__c && opp.recordtypeid==devRecordTypeId )//a3r is the starting sting in ID for all Profitability
                    {
                    att.addError('Since this opportunity was submitted for approval, you are not allowed to add a new attachment.');
                    }
                    else if(parentObjId.startsWith('a3r') && opp.Rfleet_locked__c==true && opp.id==pro.Rfleet_opportunity__c && opp.recordtypeid==devRecordTypeId1)
                    {
                    att.addError('Since this opportunity was closed, you are not allowed to add a new attachment.');
                    }
                }
            }
    }
 }
 if(trigger.isdelete && trigger.isbefore){
     for (Attachment att:Trigger.old){
      String parentObjId = att.ParentId; 
      list<opportunity> pid= [select Rfleet_locked__c,recordtypeid from Opportunity where Rfleet_locked__c=true ];// it get list of opp locked records.
               list<Rfleet_Profitability__c> ids=[Select Rfleet_opportunity__c from Rfleet_Profitability__c where id=:att.ParentId];
            for(Rfleet_Profitability__c pro:ids){
                for(opportunity opp:pid){    
                    if(parentObjId.startsWith('a3r') && opp.Rfleet_locked__c==true && opp.id==pro.Rfleet_opportunity__c && opp.recordtypeid==devRecordTypeId)//a3r is the starting sting in ID for all Profitability
                    {
                    att.addError('Since this opportunity was submitted for approval, you are not allowed to delete the attachment.');
                    }
                    else if(parentObjId.startsWith('a3r') && opp.Rfleet_locked__c==true && opp.id==pro.Rfleet_opportunity__c && opp.recordtypeid==devRecordTypeId1)
                    {
                    att.addError('Since this opportunity was closed, you are not allowed to delete the attachment.');
                    }
                }
            }
     }
 
 }
 if(trigger.isupdate && trigger.isafter){
     for (Attachment att:Trigger.new){
      String parentObjId = att.ParentId; 
      list<opportunity> pid= [select Rfleet_locked__c,recordtypeid from Opportunity where Rfleet_locked__c=true ];// it get list of opp locked records.
               list<Rfleet_Profitability__c> ids=[Select Rfleet_opportunity__c from Rfleet_Profitability__c where id=:att.ParentId];
            for(Rfleet_Profitability__c pro:ids){
                for(opportunity opp:pid){    
                    if(parentObjId.startsWith('a3r') && opp.Rfleet_locked__c==true && opp.id==pro.Rfleet_opportunity__c && opp.recordtypeid==devRecordTypeId)//a3r is the starting sting in ID for all Profitability
                    {
                    att.addError('Since this opportunity was submitted for approval, you are not allowed to update the attachment.');
                    }
                    else if(parentObjId.startsWith('a3r') && opp.Rfleet_locked__c==true && opp.id==pro.Rfleet_opportunity__c && opp.recordtypeid==devRecordTypeId1)
                    {
                    att.addError('Since this opportunity was closed, you are not allowed to update the attachment.');
                    }
                }
            }
     }
 
 }
 }


@testclass

@isTest(SeeAllData=true)
    public class Rfleet_DisableAttachements_Test {
    static testMethod void  Rfleet_DisableAttachements(){
    

    Id devRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('RFLEET-OPP-DCVF-RT').getRecordTypeId();
    Id devRecordTypeId1 = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('DC-VF Read only RT').getRecordTypeId();
    //RecordType rt = [select Id from RecordType where Name = 'RFLEET-OPP-DCVF-RT' and SobjectType = 'opportunity' LIMIT 1];
    Opportunity opp=new Opportunity();
    //opp.RecordTypeId = rt.id; 
    opp.RecordTypeId=devRecordTypeId ;
    opp.Rfleet_locked__c = True;
    
    opp.name='fdf';
    //opp.id='a3rm0000000D6Z5';
    //opp.id==pro.Rfleet_opportunity__c
    
    opp.stagename='Internal Approbation';
    opp.closedate=System.Today();
    insert opp;
    opp.stagename='Proposal to Customer';
    update opp;

    Attachment attach=new Attachment();
     //attach.id=opp.Id;
    attach.Name='TestAtt'; 
    Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body'); 
    attach.body=bodyBlob; 
    attach.parentId=opp.Id; 
    insert attach; 
    
    Rfleet_Profitability__c Pro=new Rfleet_Profitability__c();
    pro.Rfleet_opportunity__c=opp.Id;
    //pro.id=attach.id;
    
  // pro.id='a3rm0000000D6Z5';
  
           try{
          insert pro;

              }catch (DMLException e) {} 

    List<Attachment> attachments=[select id, name from Attachment where parent.id=:opp.id ];
    System.assertEquals(1, attachments.size());
     attach = [SELECT Id, name from Attachment where parent.id=:opp.id];
     //System.assertEquals(pro.Id, attach.ParentId);
     update attach;
     delete attach;  

         }
         }
trigger AccountDuplicatePreventer on Account(before insert,before update)
{
    Set<String> vSetNewPersonEmail = new Set<String>();
    Map<String, Account> OldAccounttMap = new Map<String, Account>();
    Map<String, Account> NewAccountMap = new Map<String, Account>();
   
    for(Account a: trigger.new){
   
        NewAccountMap.put(a.PersonEmail,a);
    }
    List<Account> vLstOldAccount = [SELECT Id,name,PersonEmail FROM Account WHERE isPersonAccount = true AND PersonEmail in: NewAccountMap.keyset() ];
    system.debug('this is test'+vLstOldAccount );
    If(vLstOldAccount.size()>0){
       
    for(Account b: vLstOldAccount){
        OldAccounttMap.put(b.PersonEmail,b);
    }
    for(Account a: trigger.new){
  
           a.PersonEmail.adderror('There is already another Account with the same PersonEmail.' +
                'Refer: <a href=\'/' +
                OldAccounttMap.get(a.PersonEmail) + '\'>' +
                OldAccounttMap.get(a.PersonEmail).Name + '</a>',
                FALSE
            );

 
}
}


Test Class

@isTest(SeeAllData=True)
Public Class TestcontactDuplicatePreventer
{
Static testMethod Void contactDuplicatePreventer()
{
   Account ac= new Account();
   ac.LastName='xyz';
   ac.Email__c='test@sales.com';
   ac.PersonEmail='test@ibm.com';
}
}
Controller class:
public with sharing class AccountPageSearchController
{
    public String SearchField1{get;set;}
    public String SearchField2{get;set;}
    public String SearchField3{get;set;}
    public String SearchField4{get;set;}
    public Boolean CreateNewAccount{get;set;}
    public List<Account> AccountResult{get;set;}
    public String ContractQueryString{get;set;}
    public String AccountQueryString{get;set;}
    //public RecordType RTID;
    public string RecordType;
  
    public AccountPageSearchController(ApexPages.StandardController controller)
    {
        CreateNewAccount = false;
        AccountResult = new List<Account>();
        SearchField1='';
        SearchField2='';
        SearchField3='';
        SearchField4='';
    }
   
public list<selectOption> getRecordTypes{
    get{
    if(getRecordTypes == null)
    {

             String selectedRecordType ;
            getRecordTypes = new list<selectOption>();
            Schema.DescribeSObjectResult d = Schema.SObjectType.Account;
            Map<Id,Schema.RecordTypeInfo> rtMapById = d.getRecordTypeInfosById();
            for(RecordType rt:[SELECT Id,Name FROM RecordType WHERE SobjectType='Account'])
            {
            Schema.RecordTypeInfo rtInfo =  rtMapById.get(rt.id);
            if(rtInfo.isAvailable())
            {
            getRecordTypes.add(new selectOption(rtInfo.getRecordTypeId(),rtInfo.getName()));
             if(rtInfo.isDefaultRecordTypeMapping())
             {
             selectedRecordType = rtInfo.getRecordTypeId();
             }
                }
            }
        }
             return getRecordTypes;
    }
    private set;
    }

    public pagereference searchit()
    {
        AccountQueryString='Select id,name,(select id,name,StageName from opportunities) from account where';
        String ContractQueryString='Select id,name,AccountId from contact where';
        String IdString='';
        List<id> AccId = new List<id>();
        if(SearchField2!='' && SearchField2!=null && SearchField2.length() >2)
            ContractQueryString += ' name LIKE \''+ SearchField2 +'%\'' +' and';
        if(SearchField3!='' && SearchField3!=null && SearchField3.length() >2)
            ContractQueryString += ' email = \''+ SearchField3 +'\' and';
        if(SearchField4!='' && SearchField4!=null && SearchField4.length() >2)
            ContractQueryString += ' phone= \''+ SearchField4 +'\'';
        else
            ContractQueryString=ContractQueryString.removeend(' and');
        if(SearchField1 != '' && SearchField1 != null)
            AccountQueryString += ' name LIKE \''+SearchField1+'%\'' +' and';
        system.debug('################'+ContractQueryString);
        if(SearchField2!='' || SearchField3!='' || SearchField4!='')
        {
            for(Contact Ctemp: database.query(ContractQueryString))
            {
                AccId.add(Ctemp.AccountId);
        
            }
            if(!AccId.isEmpty())
            {
                for(String Aid :AccId)
                    if(Aid !=null)
                        IdString += '\''+Aid+'\',';
                    else
                        continue;
                if(IdString == '' )
                    IdString ='\'\'';
            }
            else
                IdString ='\'\'';
            IdString = IdString.removeend(',');
                AccountQueryString +=  ' id IN('+IdString+')';
           
        }
        else if(SearchField1 == '' || SearchField1 == null)
            return null;
        else
            AccountQueryString = AccountQueryString.removeend(' and');
        System.debug(ContractQueryString+'***************'+AccountQueryString);
       
        System.debug('***************'+AccountQueryString);
        AccountResult = new List<Account>((List<Account>)database.query(AccountQueryString));
        if(AccountResult.isEmpty())
            CreateNewAccount=true;
        else
            CreateNewAccount=false;
        return null;
    }

}

Vf Page:

<apex:page standardController="Account" extensions="AccountPageSearchController" >
    <apex:outputPanel >
        <apex:form >
            <apex:pageBlock >
               
                Account Name  <apex:inputText value="{!SearchField1}"  />
                Contact Name  <apex:inputText value="{!SearchField2}" />
                Contact Email  <apex:inputText value="{!SearchField3}" />
                Contact Number  <apex:inputText value="{!SearchField4}" />
                {!ContractQueryString}
                <apex:commandButton value="Search" action="{!searchit}"/>
            </apex:pageBlock>
            <apex:pageBlock rendered="{!IF(AccountResult.size > 0,true,false)}" >
                <apex:pageBlockTable var="Acc" value="{!AccountResult}">
                    <apex:column width="10%">
                        <apex:outputLink value="/{!Acc.id}/e?retURL={!Acc.id}">Edit</apex:outputLink>
                    </apex:column>
                    <apex:column value="{!Acc.Name}" width="30%" />
                    <apex:column >

                    <apex:pageBlockTable var="Opp" value="{!Acc.Opportunities}" rendered="{!IF(Acc.Opportunities.size >0,true,false)}">
                        <apex:column width="10%">
                            <apex:outputLink value="/{!Opp.id}/e?retURL={!Opp.id}">Edit</apex:outputLink>
                        </apex:column>
                        <apex:column value="{!Opp.Name}"/>
                    </apex:pageBlockTable>
                    <apex:outputLink value="/setup/ui/recordtypeselect.jsp?ent=Opportunity&retURL=/apex/SOSL&save_new_url=%2F006%2Fe%3FretURL%3D%252F006%252Fo" rendered="{!IF(Acc.Opportunities.size == 0,true,false)}">Create Opportunity</apex:outputLink>
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlock>
            <apex:pageBlock rendered="{!CreateNewAccount}" >
                <apex:pageBlockSection >
                    <apex:inputField value="{!Account.Name}"/>
                    <apex:inputField value="{!Account.Business_Type__c}"/>
                    <apex:inputField value="{!Account.Email__c}"/>
                   
                </apex:pageBlockSection>
                <apex:pageBlockButtons >
                        <apex:commandButton value="Save" action="{!Save}"/>
                    </apex:pageBlockButtons>
            </apex:pageBlock>
        </apex:form>
    </apex:outputPanel>
</apex:page>
@isTest(SeeAllData=true)
public class TestupdateFallout
{
static testMethod  void updateFallout()
{
  Messaging.InboundEmail email = new Messaging.InboundEmail() ;
  Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
  // setup the data for the email

  email.fromAddress = 'rajat@salesforce.com';

  env.toAddress=('test_email_service@v-owqjewyhqhs8stb49ok48inl50drvv20gd0siiwzsbiu38uix.11-4ypueay.cs18.apex.salesforce.com');
 
  email.htmlBody='<?xml version="1.0" encoding="UTF-8"?><ValidateConfigResult><Configuration><ConfigId>CE05502807</ConfigId><Status>false</Status></Configuration></ValidateConfigResult>';
  
  test.startTest();
   
  updateFallout testInbound=new updateFallout();
 
   testInbound.handleInboundEmail(email,env);
      
     test.stopTest();
         

}   
}