Category Archives: Apex

Salesforce: Trigger on Attachment – Restricting user from attaching files with specific extensions

By default Salesforce don’t allow admin to configure or restrict user from adding specific type of files. Admin may need that user should not be able to attach files of type exe, dll which can have virus in them. Also there is no virus check is done when file is getting uploaded to the Salesforce.

But Salesforce does allow writing trigger on the Attachment Object by which you can implement such restrictions. Following is the snippet of the code which will restrict user from adding the files with extension mentioned in the set list. You can also edit the code and do the reverse by checking if extension exist in the set then only allow attaching the file.

trigger AttachmentTrigger on Attachment (before insert) {
set<String> setExtNotAllowed = new set<String> {‘exe’,’dll’};
for (Attachment attachment
String strFilename = attachment.Name.toLowerCase();
List<String> parts = strFilename.splitByCharacterType();
attachment.addError(‘File with extension exe or dll could not be attached!!’);

Once trigger code is up and running, whenever Salesforce tries to attach any file with extension exe or dll he will come across following error message.


Salesforce: Adding specific working days to a Date

Many time while coding we come across the requirement in which we need to calculate the Enddate from a StartDate after specific number of business/working days. That means excluding the weekends (Saturday & Sunday) Following is the code snippet which does this. I know there can be optimize way for doing this. But I didn’t wanted to spend more time on this.

Below method takes date and number of working days to be added to the date.

global Datetime addBussinessDays(Datetime startDate, Integer iDays)
Datetime endDate = startDate.addDays(iDays);
Integer iOffDays = daysOff(startDate,endDate);
return endDate.addDays(iOffDays);

Method daysOff calculates the number of non-working days coming in the start date and end date. And after which we are again adding those number of days.

global Integer daysOff(Datetime sdate, Datetime edate)
Integer iCount = 0;
while (sdate < edate) {
if (sdate.format('E') == 'Sat' | sdate.format('E') == 'Sun'){
iCount = iCount + 1;
sdate = sdate.addDays(1);
return iCount;