Magnetism and electronic structure of 3d and 4d ions in metals