Affection should only be given when the dog is being calm and submissive. Never when the dog is excited, anxious, scared, nervous etc... or you will be reinforcing that state in the dog.
Not everyone agrees with that. Dr. Patricia McConnell, for one, has another point of view.