• Salesforce Developer
  • NEWBIE
  • 250 Points
  • Member since 2014

  • Chatter
    Feed
  • 7
    Best Answers
  • 1
    Likes Received
  • 3
    Likes Given
  • 1
    Questions
  • 64
    Replies
I have got 58% code covereage for the chatterTooltip class mentioned in code sample and i am facing difficulty while increasing remaining code coverage.

Please suggest me onthis , Thanks in advance...
Class :

public class chatterTooltip {
    public string uID   { get; set; }
    
    public User u       { get; set; }
    
    public integer followers    { get; set; }
    public integer following    { get; set; }
    
    public boolean followingme  { get; set; }
    
    public string lastUpdate    { get; set; }
    public string timestr       { get; set; }
    
    public boolean isTest       { get; set; }
    
    public chatterTooltip() {
        isTest = false;
    }
    
    public string getUserName() {
        if( uID == null )
            return null;
            
        if( u != null )
            return u.name;
            
        User[] us = [select id, name 
            from User
            where id = :uID];
            
        if( us.isEmpty() )
            return '';
            
        u = us[0];
            
        loadData();
            
        return u.name;
    }
    
    public void loadData() {
        integer qlimit = ( isTest ? 1 : 1000 );
        
        EntitySubscription[] ess = [select id, parentid
            from EntitySubscription
            where parentid = :uID
            or subscriberid = :uID limit :qlimit];
            
        followers = 0;
        
        for( EntitySubscription es : ess )
            if( es.parentid == uID )
                followers++;
                
        following = ess.size() - followers;
        
        if( UserInfo.getUserId() != uID ) {
            EntitySubscription[] ess2 = [select id
                from EntitySubscription
                where parentid = :UserInfo.getUserId()
                and subscriberid = :uID];
                
            followingme = ess2.size() > 0;
        } else
            followingme = false;
            
        UserFeed[] ufs = [select id, FeedPost.body, createddate
            from UserFeed
            where parentid = :uID
            order by createddate desc limit 1];
            
        if( ufs.isEmpty() )
            return;
            
        lastUpdate = ufs[0].FeedPost.body;
        
        if( lastUpdate == null )
            return;
        
        if( lastUpdate.length() > 70 )
            lastUpdate = lastUpdate.substring( 0, 70 ) + '...';
            
        timestr = relativeTime( ufs[0].createddate );
    }
    
    public string relativeTime( Datetime dt ) {
        long diff =  ( Datetime.now().getTime() - dt.getTime() ) / 1000;
        string unit;
        
        if( diff < 60 )
            unit = 'second';
        else if( diff < 60 * 60 ) {
            diff /= 60;
            unit = 'minute';
        } else if( diff < 60 * 60 * 24 ) {
            diff = diff / 60 / 60;
            unit = 'hour';
        } else {
            diff = diff / 60 / 60 / 24;
            unit = 'day';
        }
        
        if( diff > 1 )
            unit += 's';
            
        return diff + ' ' + unit + ' ago';
    }
    
}

Test class :

@Istest 
Public class Test_chatterTooltip{

    static testmethod void runTest(){
    
            //Find user with Profile = Sales and Service
        Profile sysadm = [Select id from Profile where Name = 'System Administrator' limit 1];
        User u = new User(
            Alias = 'standt', 
            Email='standarduser@testorg.com',
            EmailEncodingKey='UTF-8',
            LastName='Testing',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            ProfileId = sysadm.Id,
            TimeZoneSidKey='America/Los_Angeles',
            UserName='standarduser@testorg.com'
            );
            
        chatterTooltip ct = new chatterTooltip();
        ct.isTest = true;
        ct.uid = UserInfo.getUserId();
        
        ct.getUserName();
        ct.relativeTime(datetime.now());      
        ct.loadData(); 
                         
      }

Uncovered code
I wrote a trigger that works perfectly in sandbox and has 83% test coverage and deployed it to production, then Trigger was worked smoothly up to 9 months,from 5days back onwords its not working in the production instance where as Working in Sandbox now also and I don't get any error messages, but the thing that it's supposed to do (Query and fill customer field in Case Based on SuppliedEmail) just doesn't happen. In production, it also has 83% coverage. Any ideas what's going on?
 
Here's the code:

Trigger CaseCustomer on Case (before insert,after update) {
    Try{
    Set<String> stemail = new Set<String>();
    List<Customer__c> custlst = new List<Customer__c>();
    Map<String,Customer__c> mpemailtocustomer = new Map<String,Customer__c>();
    List<Case> updcaselst = new List<Case>();
    Map<String,Entitlement> mpentitle = new Map<String,Entitlement>();
    Set<Id> casid = new Set<Id>();
    List<CaseMilestone> cmsToUpdate = new List<CaseMilestone>();
    
    if(Trigger.isAfter)
    {
        for(Case icas:Trigger.New)
        {
            if((trigger.newMap.get(icas.id).Status!= trigger.oldMap.get(icas.id).Status) && icas.Status == 'Closed')
            {
                casid.add(icas.id);
                System.debug(casid);
            }
        }
        if(casid.size()>0)
        {
            cmsToUpdate = [select Id,completionDate from CaseMilestone where caseId IN :casid];
            System.debug(cmsToUpdate);
        }
        if(cmsToUpdate.size()>0)
        {
            for(CaseMilestone icasn:cmsToUpdate)
            {
                icasn.completionDate = System.now();
            }
            update cmsToUpdate;
        }
        
    }
    
   else
   {
    for(Case icas:Trigger.New)
    {
        if(icas.SuppliedEmail != null)
        {
            stemail.add(icas.SuppliedEmail);
            System.debug(stemail);
        }
    }
    if(stemail.size()>0)
    {
        custlst = [SELECT ID,Email__c FROM Customer__c WHERE Email__c IN:stemail];
        System.debug(custlst);
    }
    if(custlst.size()>0)
    {
        for(Customer__c icus:custlst)
        {
            mpemailtocustomer.put(icus.Email__c,icus);
            System.debug(mpemailtocustomer);
        }
    
    }
    List<Entitlement> entlst = [SELECT id,Name FROM Entitlement];
    if(entlst.size()>0)
    {
        for(Entitlement ient :entlst)
        {
            mpentitle.put(ient.Name,ient);
        }
    }
    
        for(Case icas : Trigger.New)
        {
            if(mpemailtocustomer.containskey(icas.SuppliedEmail))
            {
                icas.Customer__c = mpemailtocustomer.get(icas.SuppliedEmail).ID;           
            }
            if(icas.Origin == 'Email' ||  icas.Origin == 'Phone' || icas.Origin == 'Web')
            {
                icas.EntitlementId = mpentitle.get('Response').Id;
                System.debug(icas.EntitlementId);
            }
        }
    
    }
    }catch(exception e)
    {
        System.debug(e.getlinenumber()+e.getmessage());
    }
}
Hi

I am trying to send an email with pdf whenever a pdf is attached in "Notes and Attachment" section. Whenever I try to upload it is giving me an error 

10:04:27:005 FATAL_ERROR System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, No body supplied for the file attachment.: [fileAttachments]

Please find the below code for Apex trigger.
trigger EmailTrigger on ContentVersion (after insert) 
{
List<Messaging.SingleEmailMessage> allMessages = new List<Messaging.SingleEmailMessage>();
for(ContentVersion cv : trigger.new)
{
Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
attachment.setBody(cv.ContentBodyId);
attachment.setFileName(cv.Title + '.' + cv.FileType);

Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.toAddresses = new String[] { 'andre.nobre@cleantechsolar.com' };
message.subject = 'Test Mail';
message.plainTextBody = 'Attached file name: ' + cv.Title;
message.setFileAttachments(new Messaging.EmailFileAttachment[] {attachment});

allMessages.add(message); 
}

Messaging.sendEmail(allMessages);
}
Kindly help me to rectify the same.
 
Requirement: If the richText field is edited, throw error.
Implementation:
One vallidation rule: ISCHANGED( RichText__c )
This rule is throwing error all the time, even if you do not edit RichText field.

Any suggestions on how to achieve the requirement with out of box functionality?

 
Hi ,

I need help for test class to cover the below class as follows, I have test class which is covering only 20% need help to cover above


 
APEX CLASS :

global with sharing class iDealPageRedirectExtn {

    public static Integer count{get; set;}
    public static Integer count2{get; set;}
    public static Integer count3{get; set;}
    public static Integer count4{get; set;}
    public iDealPageRedirectExtn(ApexPages.StandardController controller){
       
        	String accountId = ApexPages.CurrentPage().getParameters().get('id');
        if(accountId!=null){
            System.debug(count+' '+count2+' '+count3+' '+count4);
            count 	=	 0;
            count2  =	 0;
            count3	= 	 0;
            count4	=	 0;
      		 count =[select count() from Agency_Info__c where Account__c= :accountId and Recordtype.Name='Distribution' limit 1];             
        	 count2 =[select count() from Agency_Info__c where Account__c=:accountId and PCC__c!='' and Recordtype.Name='GDS' limit 1];             
             count3 =[select count() from Agency_Info__c where Account__c in (select Primary_Account__c from Account_Relation__c where Related_Account__c=:accountId and Active__c=TRUE) and PCC__c!='' limit 1];             
             count4 =[select count() from Contract__c where Account__c=:accountId];           
            System.debug(count+' '+count2+' '+count3+' '+count4);
            }
        
    }    
}

Kindly help me pls

Thanks in Advance​
I am trying to update some accounts in the anonymous window and get the Too many DML rows error message. What am I doing wrong? 
 
​List<Account> acc = new List<Account>();

for(Account a:[SELECT Id, Industry from Account WHERE Industry='Architect']){
    
    a.Industry='Architecture';
    acc.add(a);
}

update acc;

Yogesh
Hi I m little confused with the difference between issued and Dml Statements,Total number of SOQL queries issued 100, Total number of DML statements issued 150. i used FOR loop for insertion, I know its not best practice, I m trying to learn possibilities, I did nt use any soql query then why i m getting System.LimitException: Too many SOQL queries: 101, but insert is DML operation right? it should hit DML Exception 151? someone please explain me this.  

public class accountinse {
    
    public PageReference show(){
        List<Account> ac=new List<Account>();
        for(Integer i=0; i<200; i++){
            
            
            a.Name='testing12535'+i;
            a.AccountNumber='4857885';
            a.Type='Prospect';
            a.Industry='Biotechnology';
            a.AnnualRevenue=158758;
            a.Rating='cold';
            a.Phone='18578558';
            a.Identity_Proof__c='Adhar Card; PAN Card';
            a.Last_Name__c='a';
            ac.add(a);
        
        }
        insert ac;
        return null;
    }

}
Hi all,

I have a requirement to sent email alert to lead owner  and conditions are like
  1. Alert will go to lead owner after 2 hours from lead created time
  2. Lead owner will get mail only Week days and not in week ends
I am a beginner to SF coding. I am getting this error  System.LimitException: Too many query rows: 50001 at line 17

my code is this, i am not sure why i am getting this error.

public class TransferTriggerHandler {
    public static final string COMMENT_TRUNCATED_MSG = Label.Comment_Truncated_Msg;
    public void OnAfterInsert(Transfer__c[] newTransObjects){
        
        
        List<Case> caseList = new List<Case>();
        List<CaseComment> caseCommentList = new List<CaseComment>();
        Map<id,Case> caseMap =  new Map<id,Case>([Select Id,Action_Owner__c,Action_Owner_Assignee__c,Minutes_Worked__c,accountId,account.ownerId from Case]); 
       
        boolean isPublish = false;
        String comment;
        
        for(Transfer__c trans: newTransObjects) {
            comment = 'New Transfer :'+trans.Name;
            comment += ' |Assigned Group:' + (trans.Action_Owner__c != null? trans.Action_Owner__c :' ') ;
            comment += ' |Summary of Issue:' + (trans.Summary_of_Issue__c != null ? trans.Summary_of_Issue__c : ' ');
            comment += ' |Customer Hardware Details:' + (trans.Customer_Hardware_Details__c != null ? trans.Customer_Hardware_Details__c : '') ;
            comment += ' |Work Done So Far:' + (trans.Work_Done_So_Far__c !=null ? trans.Work_Done_So_Far__c : '');
            comment += ' |Evidence/Supporting Details:' + (trans.Evidence_Supporting_Details__c !=null ? trans.Evidence_Supporting_Details__c : ''); 
            comment += ' |Expected Next Actions:' + (trans.Expected_next_actions__c != null ? trans.Expected_next_actions__c : '');
            comment += ' |Escalation Reason: ' + (trans.Escalation_Reason__c != null ? trans.Escalation_Reason__c : '');
            
            if (comment.length() > maxCommentLength) {
                //This comments is too long, we need to truncate it/
                comment =  comment.substring(0, maxCommentLength) + COMMENT_TRUNCATED_MSG;                    
            }
            
            Case c = caseMap.get(trans.case__c);
            CaseComment cc = new CaseComment(CommentBody= comment, IsPublished=isPublish,ParentId= c.id);
            caseCommentList.add(cc);
            insert caseCommentList;
           
            if(trans.Action_Owner__c =='Sales'){
           
                c.Action_Owner_Assignee__c = c.account.ownerid ;
                c.Action_Owner__c =trans.Action_Owner__c;
                c.Minutes_Worked__c= trans.Minutes_Worked__c;
            }
            else{
                c.Action_Owner_Assignee__c = null;
                c.Action_Owner__c =trans.Action_Owner__c;
                c.Minutes_Worked__c= trans.Minutes_Worked__c;
            }
            caseList.add(c);
        }
        try{
            if(caseList.size() > 0) {
                update caseList;
            }
        }  
        catch (Exception e){
            System.debug('Failed in transfer trigger handler class insertion'+e);
        }          
        
    }
    

    @TestVisible private static integer maxCommentLength {
        get
        {
            List<AddTransferFieldstoCase__c> tfc = AddTransferFieldstoCase__c.getall().values();
           
            integer returnValue = 4000;
           
            if (tfc.size() > 0) {
                returnValue = (integer)(tfc[0].MaxCommentLength__c);
            }

           
            returnValue = returnValue - COMMENT_TRUNCATED_MSG.length();

            if (returnValue < 0) throw new CommentConvertException('Maximum comment length is less than Zero. Check settings.');
            return returnValue;
        }
    }
    
    public class CommentConvertException extends Exception {}
}
Hello,

I am getting the following error message when detonating this trigger below:
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger OpportunityTeamMembers caused an unexpected exception, contact your administrator: OpportunityTeamMembers: execution of BeforeInsert caused by: System.ListException: Before Insert or Upsert list must not have two identically equal elements: Trigger.OpportunityTeamMembers: line 28, column 1​
 
trigger OpportunityTeamMembers on Opportunity (before insert) {
    List<OpportunityTeamMember> myOpptyTeamMembers = new List <OpportunityTeamMember>();
    for(Opportunity myOpp : Trigger.new){
        //Create an Oppty Team Member
        OpportunityTeamMember otm = new OpportunityTeamMember();
        otm.opportunityId = myOpp.Id;
        // If a Manager exist, add it to the list of myOpptyTeamMembers
        if(myOpp.Owner.ManagerId != null){
            otm.userId = myOpp.owner.ManagerId;
            otm.TeamMemberRole = 'Sales Manager';
            myOpptyTeamMembers.add(otm);
        }
        // If Dependents exist, add it/them to the list of myOpptyTeamMembers
        List<User> dependentUsers = [SELECT Id
                                     FROM User
                                     WHERE ManagerId = :myopp.OwnerId];
        if(dependentUsers.size()>0){
            // Loop on dependentUsers List
            OpportunityTeamMember otm2 = new OpportunityTeamMember();
            for(User myDependentUser : dependentUsers){
                otm2.UserId         = myDependentUser.Id;
                otm2.TeamMemberRole = 'Sales Rep';
                myOpptyTeamMembers.add(otm2);
            }
        }
    }
    // Add/Insert Team Members to the myOpp
    insert myOpptyTeamMembers;
}

According to the error message, it sounds like I am trying to insert a List (myOpptyTeamMembers) with two identical items (?).
I guess that, to Salesforce, two identical items would be identicals if their Id were the same, right? This would mean that, in myOpptyTeamMembers (which is the list I am inserting at the end of the code), there are 2 records Opportunity Team Members with the same Id?
How could this be possible?
Any clue?
(Thank you very much)
We currently have a trigger that was set up by a third party vendor automatically adds an Account Team based on the linked account data of our syncing database.  There is one representaive that the trigger doesn't seem to be recognizing.

I'm unfamiliar with the coding to be able to pin point the issue.  Is there anyone that can point me in the direction of a solution?

trigger AddAccountTeamMembers on Account (after insert,after update){
 //Get User's Name,Id and Store into userMap
   Map<String,Id> userMap=new Map<String,Id>();
   List<Id> userIds= New List<Id>();
   for(User u:[Select id,name from user]){
       userMap.put(u.name,u.id);
       userIds.add(u.Id);
    }
  if(trigger.isInsert && trigger.isAfter){
    Set<Id> repId=new Set<Id>();
    Set<Id> accList=new Set<Id>();
    List<AccountTeamMember> memberList=new List<AccountTeamMember>();   
  //Add account repid and account id's
    for(Account acc : trigger.new){
      repId.add(acc.OASP__OAS_Rep__c);
      accList.add(acc.id);
    }
    Map<id,String> conMap=new Map<id,String>();
  //Query the contacts with account RepId's
    if(repId != null && !repId.isEmpty()){
       for(Contact con: [Select id,name from Contact where Id In:repId]){
          conMap.put(con.id,con.name);
       }
    }
    for(Account acc : trigger.new){
  //Splitting the contacts
     String contactName = conMap.get(acc.OASP__OAS_Rep__c);
     if(contactName!=null){
        List<String> conSplit=contactName.Split(' and ');
  //Add the contacts into Account Team Members
        for(String temp: conSplit){
             AccountTeamMember accMember=new AccountTeamMember();
             accMember.TeamMemberRole='Account Manager';
             accMember.AccountId=acc.id;
             accMember.UserId=(Id)userMap.get(temp);
             memberList.add(accMember);
             
        }
      } 
    } 
    System.debug('++Acc Team Member++'+memberList);
   //insert the contacts and Sharing rules
    if(memberList!=null){
      Database.insert(memberList,false);
    }
    System.debug('++Account List++'+accList);
    //Use future method for Insert Account Share Access
    if(accList != null && accList.size()>0 && memberList.size()>0)
    FutureAccountShare.updateAccountShareAccess(accList);
  }
  if(trigger.isUpdate && trigger.isAfter){
    Set<Id> accId=new Set<Id>();
    Set<Id> repId=new Set<Id>();
    Map<String,AccountTeamMember> accTeamMap = New Map<String,AccountTeamMember>();
    list<AccountTeamMember> accmemlist = New list<AccountTeamMember>();
    list<AccountTeamMember> accteamMembers = New list<AccountTeamMember>();
    Map<id,String> conMap=new Map<id,String>();   
    Set<AccountTeamMember> uniquedelete = new Set<AccountTeamMember>();
    
     for(Account acct: trigger.new){
        accId.add(acct.Id);
        repId.add(acct.OASP__OAS_Rep__c);
     }
     for(Account acct: trigger.old){
        repId.add(acct.OASP__OAS_Rep__c);
     }
     
     For(AccountTeamMember acctmem: [Select id,AccountId,UserId,AccountAccesslevel,TeamMemberRole  from AccountTeamMember where AccountId In: accId]){
          accTeamMap.put(acctmem.AccountId+'&'+acctmem.UserId,acctmem);
          accmemlist.Add(acctmem);
     }
     if(repId != null && !repId.isEmpty()){
       for(Contact con: [Select id,Name from Contact Where ID IN: repId]){
         conMap.put(con.id,con.name);
       }
     }
     Set<Id> accupdateId=new Set<Id>();
     for(Account temp: trigger.New){
      if(temp.OASP__OAS_Rep__c != Trigger.oldMap.get(temp.id).OASP__OAS_Rep__c){
       accupdateId.add(temp.Id);
       for(Id userTemp: userIds){
        String Name = conMap.get(Trigger.oldMap.get(temp.id).OASP__OAS_Rep__c);
        if(Name!=null){
        List<String> contSplitdelete =Name.Split(' and ');
         for(String str: contSplitdelete){
            AccountTeamMember AccmemId = accTeamMap.get(temp.Id+'&'+userMap.get(str)); // 
            if(AccmemId != null) {
              uniquedelete.add(AccmemId);
            }
          }
        }
       }
      } 
     }
     if(uniquedelete!=null){ 
         List<AccountTeamMember> finalDelete = new list<AccountTeamMember>();
         finalDelete.addALL(uniquedelete);
         Database.delete(finalDelete,false);
     }
     List<AccountTeamMember> teamMember=new List<AccountTeamMember>();
        for(Account accUpdate : trigger.new){
        if(accUpdate.OASP__OAS_Rep__c != Trigger.oldMap.get(accUpdate.id).OASP__OAS_Rep__c){
         String contName = conMap.get(accUpdate.OASP__OAS_Rep__c);
          if(contName!=null){
             List<String> contSplit=contName.Split(' and ');
             for(String temp1: contSplit){
                AccountTeamMember acctMember=new AccountTeamMember();
                acctMember.TeamMemberRole='Account Manager';
                acctMember.AccountId=accUpdate.id;
                acctMember.UserId=(Id)userMap.get(temp1);
                teamMember.add(acctMember);          
             }
          }
        } 
        }
     if(teamMember!=null){
     //Insert Account Team Members and Sharing rules for update
      Database.insert(teamMember,false);
     }
 //Use future method for Update Account Share Access
 if(accupdateId != null && accupdateId.size()>0){
    FutureAccountShare.updateAccountShareAccess(accupdateId);
  }
  }
}
I have an Apex Class that generates a List of Events:
 
Public class AgentAppointmentsPast30 {
    
	String sortOrder = ' Who.Name ';
    String ascendingOrDescending = ' ASC ';
    String UserID = UserInfo.getUserId();
    String dateTimeFormat = DateTime.now().format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');
    
    String myRequest = 'SELECT id, Owner.Id, type, subject, Decision_Made_by_Client__c, Appointment_Result__c, Reason_for_Cancellation_No_Show__c,'+
                ' WhoId, Who.Name, Appoint_Set_By__c, ActivityDateTime, No_Show_Cancelled_Disposition__c,Request_to_Shuffle__c,Contact_Name__r.Actual_Sale_Date__c, Contact_Name__r.Foreclosure_Status__c, Contact_Name__r.FAIR_Packet__c,'+ 
        	    ' Contact_Name__c, Contact_Name__r.Name, Contact_Name__r.Id, Contact_Name__r.Account.Property_Address__c,Contact_Name__r.Account.Name, Contact_Name__r.Account.Id'+
                ' FROM Event ' + 
                ' WHERE Owner.Id = \''+UserId+'\' And RecordTypeId = \'0126A0000004Qle\' AND ( ActivityDateTime = LAST_N_DAYS:30 OR (ActivityDateTime = TODAY And Type != \'Appointment - Booked\' And Type != \'Appointment - Confirmed\' ))'+
				' ORDER BY ';

    
    	public void sortByContact() 	{this.sortOrder = ' Who.Name ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
   		public void sortByActivityDateTime() 	{this.sortOrder = ' ActivityDateTime ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByType() 	{this.sortOrder = ' Type ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortBySubject() 	{this.sortOrder = ' Subject ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByOutcome() 	{this.sortOrder = ' Decision_Made_by_Client__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByOutcomeNotes() 	{this.sortOrder = ' Appointment_Result__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByNoShowDisp() 	{this.sortOrder = ' No_Show_Cancelled_Disposition__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByNoShowReason() 	{this.sortOrder = ' Reason_for_Cancellation_No_Show__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByAddress() 	{this.sortOrder = ' Contact_Name__r.Account.Name ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}
    
    	public void sortByPacket() 	{this.sortOrder = ' Contact_Name__r.FAIR_Packet__c ';
                                   if(ascendingOrDescending ==' ASC ') 
                                   {ascendingorDescending = ' DESC ';}
                                   else{ascendingorDescending = ' ASC ';}}



        List<Event> events;
     	public List<Event> getEvents() {
		events = new List<Event>();
        events = Database.query(myRequest + sortOrder + ascendingOrDescending);
        system.debug(events);
        return events;}

  		public void saveAndReturn() {
        update events;        
        }
}
I use the following test class:
 
@isTest
public class AgentAppointmentsPast30Test {
    
    static testMethod void TestApptPast30(){
        
        Account Testaccount = new account();
       	Testaccount.name = '123 Test Drive';
        Testaccount.RecordTypeId = '0126A0000004Qo4';
        Testaccount.APN__c = '123';
        Testaccount.OwnerId = '0056A000000HeMZ';
        insert Testaccount;
        
        Contact Testcontact = new contact();
        Testcontact.Lastname = 'Berenato';
        Testcontact.AccountId = Testaccount.Id;
        Testcontact.RecordTypeId = '0126A0000004QlU';
        Testcontact.OwnerId = '0056A000000HeMZ';
        insert Testcontact;
        
        Event Testevent = new event();
		Testevent.WhoId = Testcontact.id;        
        Testevent.Subject='Test';
        Testevent.type='Appointment - Booked';
        Testevent.RecordTypeId = '0126A0000004Qle';
        Testevent.ActivityDateTime=date.valueOf('2017-10-17 11:00:00z');
        Testevent.DurationInMinutes=120;
        insert Testevent;
        
        AgentAppointmentsPast30 at = new AgentAppointmentsPast30();
      	List<Event> list1 = at.getEvents();
        at.saveAndReturn();
        at.sortByActivityDateTime();
        at.sortByAddress();
        at.sortByContact();
        at.sortByNoShowDisp();
        at.sortByNoShowReason();
        at.sortByOutcome();
        at.sortByOutcomeNotes();
        at.sortByPacket();
        at.sortBySubject();
        at.sortByType();
        system.assertEquals(1, list1.size());
    }
}

I've never been able to have the event from the Test Class meet the criteria from the Apex Class, I always get the error:

System.AssertException: Assertion Failed: Expected: 1, Actual: 0

Even if I remove everything from the WHERE clause except the getUserId.

However, my Visualforce page in the Sandbox seems to be working fine, minus one major error.

If I assign two events to myself, I see them both in the Apex PageBlockTable.

User-added image

If I edit the event that is farther in the future, I click the Save Button I added to the table.

User-added image

The page reloads:

User-added image

The records are sorted by ActivityDateTime.

And then I manually refresh the page.

User-added image

And the event that was originally farther in the past gets automatically updated to match the new events edit.

As if the Save button is saving the new value to all of the records.

I'm totally stumped on how this is happening. I can't seem to find any workflow rule that would suggest this, and I've tested it several times outside of the PageBlockTable (in the Event's Detail page) and can't find proof that it updates both records independently.

Does anyone know what might be causing this, or why my Apex Class can't pass its test?



 
Hi guys,
i have requirement like this..

for example i have two fileds in my system. one is Number of views and pdfURL.

i have added one url link to pdfURL. when i am going to click that url field i need to display number of views field is 1

if i will going to click 10 times that link value number of views field should be 10.

Please help me on this urgent.

thanks advacne
Hi,
 
Can someone explain to me how to write a test class for an apex trigger like the following one ? This trigger assigns new Leads in Salesforce to the existing Account owner if the domain email address matches the Account's domain.

I'm new to writing Apex but it is working in the Sandbox. I just need a test class to be able to deploy it to Production.


Thanks 

 
trigger addAccount on Lead (before insert){

    //Use a set instead of a list to gather all of the unique domains
    Set<String> leadDomains = new Set<String>();

    //Loop through leads to populate the set
    for(Lead l : trigger.new){
        leadDomains.add(l.domain__c);
    }

    //Query for accounts
    List<Account> leadAccounts = [Select Id, OwnerId, domain__c From Account Where domain__c = :leadDomains];

    //Create Map and loop through list to populate the map
    Map<String,Account> accMap = new Map<String,Account>();
    for(Account a : leadAccounts){
        accMap.put(a.domain__c,a);
    }

    //Loop through leads and assign correct owner from Map
    for(Lead l2 : trigger.new){
        if(accMap.containsKey(l2.domain__c)){
            l2.OwnerId = accMap.get(l2.domain__c).OwnerId;
            l2.Existing_Account__c = true;
            
         
        }
        else{
           
        }
    }


}

 
Hi, i want to write trigger code for the following requirement. i have two objects courses and students .
in course object i have two fields coursename and no of students. in student object i have Name and a lookup field (with course object). if a student  select a course the no of student field count should be incresed.if i delete a student  the count should be decresed.
Hello, I have a custom button with this conditional logic:
if('{!User.ProfileId}'!=='00e40000000zCOY')
{
window.alert("You do not have permission to send survey");
}
else
blah blah blah

This looks to make sure the person pushing the button has the right profile.  It works fine but now I want to add another profile that would be allowed.  So if not profile 1 OR not profile 2, fire the window alert, else go ahead and do something.

If tried multiple things but can't get it to work.  Any suggestions would be appreciated.

Recently, I was writing some classes that needed to detect if the org they were in was a sandbox or not and determine which endpoint to call accordingly. Since there isn's an isSandbox method in Apex, I had to create my own. This will work in visualforce controllers/extensions and from standard classes. You can read the full details at http://www.ericsantiago.com/eric_santiago/2011/12/determining-salesforce-server-pod-and-if-sandbox-via-apex.html

 

Code as follows

 

public String currentPod { 
            String server;
            
            if (ApexPages.currentPage() != null){ //called from VF page
            		server = ApexPages.currentPage().getHeaders().get('X-Salesforce-Forwarded-To');
            } else { //called via standard class
            		server = URL.getSalesforceBaseUrl().getHost();
            }
            
            if ( server != null && server.length() > 0){
                server = server.substring(0 ,server.indexOf('.'));
                
            }
            return server ; 
   }

   public Boolean isSandbox {
            String pod = currentPod();
            if (pod != null && pod.length() > 0 && pod.toUpperCase().startsWith('C')){
                return true;
            }
            return false;
   }