Theory of electronic defects: Applications to MgO and alkali halides