Search In This Blog

2016-09-28

Changing a user's email address without confirmation.

When try to change user's email, Salesforce will send a confirmation mail to new email address and a notification mail to old email address in security purpose.But sometimes user don't want to get further notifications.

To avoid send notification mail to old email, try ways follow. (All ways are no working with owner)

Way 1. Set Setup | Manage | User Management | Users
When change the email address, "Generate new password and notify user immediately" checkbox (at the bottom of the edit screen) need to be checked. Then the email address will get committed right away, no more confirmation needed! But obviously the user then gets sent a new password.


Way 2. Change email through Develop console
1.Select user data [select id,email,username from user]
2.Change the target user's email and click [Save Rows]
3.Click [Refresh Grid] to check if email is been changed.
*(2016/09/28) Some license may not working, like "Company Communities".


Way 3. Change email by code
User user = [select id,email from user where id = 'target user id'];
user.email = 'new_email@exmple.com';
update user;
*If use upsert, it will have a error: "DML not allowed on User". No matter if the record already exists or updating or creating new
*(2016/09/28) Some lisence may not working, like "Company Communities"
*(2021/11/5 update) Looks like Salesforce had removed Way 3 completely.

2016-09-27

[Regex]Check English / Spanish / Franch / Arabic characters

Keep these here as a memo.


English characters:
Public Boolean checkEnglish(String value){
    return Pattern.matches('[^a-zA-Z0-9 ]+', value);
}

Spanish characters:
Public Boolean checkSpanish(String value){
    return Pattern.matches('^[0-9a-zñáéíóúü]+', value);
}

France characters:
Public Boolean checkFrance(String value){
    return Pattern.matches('[^a-zA-Z0-9 àâäèéêëîïôœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ]', value);
}

How to write Apex test class


An Apex test class is used to confirm if instructions and methods in an application or program are working correctly as desired. Tests can be written for many classes.

Since Salesforce require at least 75% of the code to be tested before it can be deployed to the organization. There are different test classes run to achieve the 75% minimum requirement tests on task codes.

To create an Apex class: [Setup]-[Develop]-[Apex Classes]-[New].
It can also be create through develop console, [You username]-[Develop console]-[File]-[New]-[Apex Class]

Basic strunction of test class
@isTest 
public class BaseTest { 
    // Test Method 
    public static testmethod void Test1(){ 
        // Prepara data for test
        List<Account> accounts = new List<Account>{};
        for(Integer i = 0; i < 200; i++){
            Account a = new Account(Name = 'Test ' + i);
            accounts.add(a);
        }
        Test.startTest(); 
        // Put test target here
        insert accounts;
        Test.stopTest();  
    } 
} 

2016-09-26

Loops in Apex class

For now(2016/9/26), Apex supports do-while, while, and for loops.

do-while:
Integer count = 1;
do {
    System.debug('count' + count);
    count++;
} while (count < 3);

while:
Integer count = 1;
while (count < 4) {
    System.debug('count' + count);
    count++;
}

for(loop in array):
Integer[] is = new Integer[]{1,2,3,4,5};
for (Integer i: is) {
 System.debug(i);
}
Queries can also be embedded in the special for syntax.
for (Test__c tmp : [SELECT Id FROM Test__c]) {
   // ...
}

2016-09-21

Use template in Visualforce page

If pages have same part like header or footer, use page template will be more efficient.

Salesforce provides some page template. For example, when you create a community site, Salesforce will create a page template named CommunitiesTemplate.

<apex:page showHeader="false" sidebar="false" id="CommunitiesTemplate">
  <apex:stylesheet value="{!$Site.Prefix}/communities/CommunitiesStyles.css"/>
  <apex:insert name="header"/>
  <apex:insert name="body"/>
  <apex:insert name="footer"/>
</apex:page>

<apex:insert name="header"/> is the header part.
<apex:insert name="body"/> is the main content part.
<apex:insert name="footer"/> is the footer part.

<!-- Import template by id -->
<apex:composition template="CommunitiesTemplate">
       <apex:define name="header">This is header used to contain something like: logo, nav menu...</apex:define>
       <apex:define name="body">This is the body  used to contain contents and sidebar.</apex:define>
       <apex:define name="footer">This is the footer. Usually use to contain copyright.</apex:define>
</apex:composition>

2016-09-17

How to validate email address with Regex expression in Visualforce page by Apex

When user input email address in Visualforce page, normally need to input the email address again as a confirm email address to make cross check.

If you create a field to save confirm email address. For example, this email address will be saved to Field(Email) in object(Contact), and use inputField tag will be convenient.
<apex:inputField value="{!Contact.Email}"/>
When you try to save, Salesforce will make the format check for you.

But if confirm email address is not a field in object, you may need to check format of confirm email address by Apex. Use Pattern.matches() will be a choice.
Regex foremail format check:
'^([0-9a-zA-Z+_.-]*[0-9a-zA-Z]+[@][0-9a-zA-Z+_.-]+\\.[0-9a-zA-Z+_.-]*)$'
*example email: huang.hai@randsfdc.blogspot.jp

Return the result of format check:
return Pattern.matches('^([0-9a-zA-Z+_.-]*[0-9a-zA-Z]+[@][0-9a-zA-Z+_.-]+\\.[0-9a-zA-Z+_.-]*)$', val); 
*val is the value of email address

To check are these two email address same, you can use String.equals(). Like: emailOne.equals(emailTwo).

String.equals(): Upper char and lower char will be treated as different char.

How to get random strings by Apex?

This post will introduce how to make a random string for using as a token or as a special code.

First, make sure what string you want to get. If you just want a random string within all number, use Math.random() and do for loop will be a easy way. But if you want to pick up the chars or numbers from a special list, try below.

// the list that you want to pick chars and numbers from
String CharList = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_';

// position in list, count will start from 0. EX. 'a' is in position 0, 'b' is in position 1
Integer position;

// length of random strings, ex. 20
Integer LengthRequired = '20';

// get 20 chars from list randomly
for(Integer i = 0; i <= LengthRequired; i++) {

    position = Integer.valueof(String.valueof(Math.roundToLong(CharList.length()*Math.random()))) -1;

    // the random Strings
    String Res += CharList.substring(position,position+1);

}

2016-09-09

How to set robots.txt file for force.com site?

When use force.com to public a website, it will be unsure whether the site can be indexed by google search engine or not if you don't set Site Robots.txt. Normally it is hard to be indexed.

To make it 100% can be indexed, it is better to create a robots.txt file. It is easy to use Visualforce page to create one.

Step 1.
New a Visualforce page. Ex. named as 'robots'.

Step 2.
Set contentType of tag <apex:page> as 'text/plain' to make Visualforce page 'robots' will be treat as a text file. As below:
<apex:page contentType="text/plain">
User-agent: *
Disallow:
Allow: /
</apex:page>
*If there are something that don' t want to be indexed, you can disallow they. Ex. 'Disallow: /unindexed_page/'. Same to Allow.

By the way, it will be unindexed as follow:
<apex:page contentType="text/plain">
User-agent: *
Disallow:/
Allow:
</apex:page>
Step 3.
Set Site Robots.txt. In Setup | Develop | Sites | Edit
Use magnifier glass mark to find the Visualforce page 'robots' or just input the name, and save.

2016-09-08

Bounced email: all failed error mail:#< #5.3.0> #SMTP#

Try to do some test cases, I sent a lot of mails(more than 60) to invalid mail address by mail alert through SFDC workflow.

#Workflow rule: When create an new record, a mail will be sent to the invalid email.

After some a lot failed mail, I sent a mail to available email, but it was failed either.

#Debug log shows mail was sent out by workflow, but I can't find the mail in inbox of "sample@mail.com".

#Get error info from error mail as "sample@mail.com#< #5.3.0> #SMTP#"

As email received succeed just before the test and the mails from salesforce isn't in block list. It should not be the problem in mail setting.

Check Configure Deliverability Settings says:
Bounced email
Email that is addressed to an invalid recipient and returned to the sender. If a sender sends several email messages that bounce, the email server might slow or block the delivery of all email from that sender.
It looks like the reason why mail can't be received. So wait the next day(UTC00:00) and it is fixed.

2016-09-06

How to get time in Salesforce?

There are a few way to get time.
1. Date.today()
  Returns the current date in the current user's time zone.
  Return Type: Date
  More info:Date Class

2. System.now()
  Returns the current date and time in the GMT time zone.
  Return Type: Datetime
  More info:System Class

3. datetime.now()
  Returns the current Datetime based on a GMT calendar.
  Return Type: Datetime
  The format of the returned datetime is: 'MM/DD/YYYY HH:MM PERIOD'
  More info: Datetime Class

4.datetime.now().time()
  Returns the current time based on a GMT calendar.
  Return Type: Time
  The format of the returned time is: 'HH:MM PERIOD'

5.datetime.now().getTime()
  Returns the current time from 1970/1/1.
  Return Type: Integer

6.NOW()
  Returns the current Datetime based on a GMT calendar.
  Return Type: Datetime


2016-09-02

Use Apex class to redirect page

Use Apex class to do this action: When open page 'RedirectPage', move to 'TargetPage' directly.

RedirectPage is name of Visualforce page
Code:
<apex:page controller="RedirectCtrl" action="{!doRedirect}">
    Redirect to TargetPage directly...
</apex:page>

RedirectCtrl is name of Apex class that use to control 'RedirectPage'
Code:
public class RedirectCtrl {
   // create redirect function
   public PageReference doRedirect() {
        // set target page
        PageReference pageRef = Page.TargetPage;
        // set a parameter to url, format 'site.com?PARAME_TYPE=PARAME_TYPE_STR'
        pageref.getParameters().put('PARAME_TYPE','PARAME_TYPE_STR');
        // do page redirect
        pageRef.setRedirect(true);
       // begin to redirect
        return pageRef;
    }
}

TargetPage is name of Visualforce page that 'RedirectPage' will redirect to.
Code:
<apex:page>
    This is target page of redirect action.
</apex:page>

That is all.