Solution for "Object reference not set" (plus unique filename suggestion)

Jun 29, 2013 at 12:32 PM
When I first started to use Spotify Recorder, I got the error message "Object reference not set to an instance of an object" after every completed recording. I downloded the source code and soon found cause of the error. Instead of selecting a different bitrate by clicking the dropdown arrow, I just typed in 192. This caused the bitrateComboBox.SelectedItem to be null instead of an int. The short term solution is to select a different bitrate by clicking the dropdown arrow, NOT by entering a new value in the text field. For the next software release, I would suggest setting the DropDownStyle property of the combo box to DropDownList instead of DropDown. This applies to deviceListBox as well.

A have another suggestion for the next software release: Since Spotify often continues to play related songs even when the queue is empty, a recorded song might be replaced by the first few seconds of the same song. I have implemented a unique filename approach to solve this, adding (1), (2) etc to the end of the song name.
        private string PostProcessing(string song)
        {
            string output = GetUniqueSongname(song);
            int bitrate = (int) bitrateComboBox.SelectedItem;
            Task t = new Task(() => ConvertToMp3(song, bitrate, output));
            t.Start();
            return output;
        }

        private string GetUniqueSongname(string song)
        {
            string result = song;
            int uniqueId = 0;
            while(File.Exists(CreateOutputFile(result, "mp3")))
              result = song + " (" + (++uniqueId) + ")";
            return result;
        }

        private void ConvertToMp3(string song, int bitrate__, string output__)
        {
        [...]
            process.StartInfo.Arguments = string.Format("-b {2} --tt \"{3}\" --ta \"{4}\"  \"{0}\" \"{1}\"",
                CreateOutputFile(song, "wav"),
                CreateOutputFile(output, "mp3"),
                bitrate,
                tag.Title,
                tag.Artist);
        [...]
        }

        private void StopRecording()
        {
        [...]
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        song = PostProcessing(song);
                        int newItemIndex = listBoxRecordings.Items.Add(song);
                        listBoxRecordings.SelectedIndex = newItemIndex;
                    }
                }
            }
        }