To avoid side effects like moving the point (that is, the cursor), wrap your movement commands in save-excursion. Prior Emacs 25 this also saved the mark (the other end of the selected region). Now to save the mark as well use save-mark-and-excursion.
First we need a function to select the whole line:
(defun mark-whole-line ()