From 96bcb7bd368315d41776c305dd290e95865f61ce Mon Sep 17 00:00:00 2001 From: "Johnny Dellinger @PC" Date: Wed, 28 Oct 2015 17:05:09 +0100 Subject: [PATCH] Some more refactoring. --- SpotifyAPI.Example/LocalControl.cs | 10 ++-- SpotifyAPI.Example/WebControl.cs | 4 +- SpotifyAPI/Local/RemoteHandler.cs | 2 +- SpotifyAPI/Local/SpotifyLocalAPI.cs | 3 +- SpotifyAPI/Local/VolumeMixerControl.cs | 64 ++++++++++----------- SpotifyAPI/Web/Auth/AutorizationCodeAuth.cs | 13 ++--- SpotifyAPI/Web/Auth/ImplicitGrantAuth.cs | 15 +++-- SpotifyAPI/Web/SimpleHttpServer.cs | 50 ++++++++-------- SpotifyAPI/Web/SpotifyWebAPI.cs | 2 +- 9 files changed, 76 insertions(+), 87 deletions(-) diff --git a/SpotifyAPI.Example/LocalControl.cs b/SpotifyAPI.Example/LocalControl.cs index f43c34e4..723e3ff6 100644 --- a/SpotifyAPI.Example/LocalControl.cs +++ b/SpotifyAPI.Example/LocalControl.cs @@ -33,26 +33,26 @@ namespace SpotifyAPI.Example { if (!SpotifyLocalAPI.IsSpotifyRunning()) { - MessageBox.Show("Spotify isn't running!"); + MessageBox.Show(@"Spotify isn't running!"); return; } if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { - MessageBox.Show("SpotifyWebHelper isn't running!"); + MessageBox.Show(@"SpotifyWebHelper isn't running!"); return; } bool successful = _spotify.Connect(); if (successful) { - connectBtn.Text = "Connection to Spotify successful"; + connectBtn.Text = @"Connection to Spotify successful"; connectBtn.Enabled = false; UpdateInfos(); _spotify.ListenForEvents = true; } else { - DialogResult res = MessageBox.Show("Couldn't connect to the spotify client. Retry?", "Spotify", MessageBoxButtons.YesNo); + DialogResult res = MessageBox.Show(@"Couldn't connect to the spotify client. Retry?", @"Spotify", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) Connect(); } @@ -109,7 +109,7 @@ namespace SpotifyAPI.Example private void _spotify_OnTrackTimeChange(TrackTimeChangeEventArgs e) { - timeLabel.Text = FormatTime(e.TrackTime) + "/" + FormatTime(_currentTrack.Length); + timeLabel.Text = $"{FormatTime(e.TrackTime)}/{FormatTime(_currentTrack.Length)}"; timeProgressBar.Value = (int)e.TrackTime; } diff --git a/SpotifyAPI.Example/WebControl.cs b/SpotifyAPI.Example/WebControl.cs index 0a06679f..8fc82080 100644 --- a/SpotifyAPI.Example/WebControl.cs +++ b/SpotifyAPI.Example/WebControl.cs @@ -42,12 +42,12 @@ namespace SpotifyAPI.Example if (state != "XSS") { - MessageBox.Show("Wrong state received.", "SpotifyWeb API Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(@"Wrong state received.", @"SpotifyWeb API Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (token.Error != null) { - MessageBox.Show("Error: " + token.Error, "SpotifyWeb API Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Error: {token.Error}", @"SpotifyWeb API Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } diff --git a/SpotifyAPI/Local/RemoteHandler.cs b/SpotifyAPI/Local/RemoteHandler.cs index c54608d8..485d28db 100644 --- a/SpotifyAPI/Local/RemoteHandler.cs +++ b/SpotifyAPI/Local/RemoteHandler.cs @@ -35,7 +35,7 @@ namespace SpotifyAPI.Local internal async void SendPlayRequest(String url, String context = "") { // TODO: instead of having an empty context, one way to fix the bug with the playback time beyond the length of a song would be to provide a 1-song context, and it would be fixed. - await QueryAsync(string.Format("remote/play.json?uri={0}&context={1}", url, context), true, true, -1); + await QueryAsync($"remote/play.json?uri={url}&context={context}", true, true, -1); } internal async void SendQueueRequest(String url) diff --git a/SpotifyAPI/Local/SpotifyLocalAPI.cs b/SpotifyAPI/Local/SpotifyLocalAPI.cs index 7d5ae8a6..0c72ab6e 100644 --- a/SpotifyAPI/Local/SpotifyLocalAPI.cs +++ b/SpotifyAPI/Local/SpotifyLocalAPI.cs @@ -2,7 +2,6 @@ using System; using System.ComponentModel; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.IO; using System.Runtime.InteropServices; using System.Timers; @@ -216,7 +215,7 @@ namespace SpotifyAPI.Local if (Environment.OSVersion.Version.Minor == 0) throw new NotSupportedException("This feature is only available on Windows 7 or newer"); if (volume < 0 || volume > 100) - throw new ArgumentOutOfRangeException("Volume parameter has to be a value between 0 and 100"); + throw new ArgumentOutOfRangeException(nameof(volume)); VolumeMixerControl.SetSpotifyVolume(volume); } diff --git a/SpotifyAPI/Local/VolumeMixerControl.cs b/SpotifyAPI/Local/VolumeMixerControl.cs index 4a6c9f12..f3fdbb2b 100644 --- a/SpotifyAPI/Local/VolumeMixerControl.cs +++ b/SpotifyAPI/Local/VolumeMixerControl.cs @@ -6,11 +6,11 @@ namespace SpotifyAPI.Local { internal class VolumeMixerControl { - private const String SPOTIFY_PROCESS_NAME = "spotify"; + private const String SpotifyProcessName = "spotify"; internal static float GetSpotifyVolume() { - Process[] p = Process.GetProcessesByName(SPOTIFY_PROCESS_NAME); + Process[] p = Process.GetProcessesByName(SpotifyProcessName); if (p.Length == 0) throw new Exception("Spotify process is not running or was not found!"); @@ -19,7 +19,6 @@ namespace SpotifyAPI.Local ISimpleAudioVolume volume = GetVolumeObject(pid); if (volume == null) { - Marshal.ReleaseComObject(volume); throw new COMException("Volume object creation failed"); } @@ -31,7 +30,7 @@ namespace SpotifyAPI.Local internal static bool IsSpotifyMuted() { - Process[] p = Process.GetProcessesByName(SPOTIFY_PROCESS_NAME); + Process[] p = Process.GetProcessesByName(SpotifyProcessName); if (p.Length == 0) throw new Exception("Spotify process is not running or was not found!"); @@ -40,7 +39,6 @@ namespace SpotifyAPI.Local ISimpleAudioVolume volume = GetVolumeObject(pid); if (volume == null) { - Marshal.ReleaseComObject(volume); throw new COMException("Volume object creation failed"); } @@ -52,7 +50,7 @@ namespace SpotifyAPI.Local internal static void SetSpotifyVolume(float level) { - Process[] p = Process.GetProcessesByName(SPOTIFY_PROCESS_NAME); + Process[] p = Process.GetProcessesByName(SpotifyProcessName); if (p.Length == 0) throw new Exception("Spotify process is not running or was not found!"); @@ -61,7 +59,6 @@ namespace SpotifyAPI.Local ISimpleAudioVolume volume = GetVolumeObject(pid); if (volume == null) { - Marshal.ReleaseComObject(volume); throw new COMException("Volume object creation failed"); } @@ -72,7 +69,7 @@ namespace SpotifyAPI.Local internal static void MuteSpotify(bool mute) { - Process[] p = Process.GetProcessesByName(SPOTIFY_PROCESS_NAME); + Process[] p = Process.GetProcessesByName(SpotifyProcessName); if (p.Length == 0) throw new Exception("Spotify process is not running or was not found!"); @@ -81,7 +78,6 @@ namespace SpotifyAPI.Local ISimpleAudioVolume volume = GetVolumeObject(pid); if (volume == null) { - Marshal.ReleaseComObject(volume); throw new COMException("Volume object creation failed"); } @@ -93,14 +89,14 @@ namespace SpotifyAPI.Local private static ISimpleAudioVolume GetVolumeObject(int pid) { // get the speakers (1st render + multimedia) device - IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator()); - IMMDevice speakers; - deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers); + IMmDeviceEnumerator deviceEnumerator = (IMmDeviceEnumerator)(new MMDeviceEnumerator()); + IMmDevice speakers; + deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.ERender, ERole.EMultimedia, out speakers); // activate the session manager. we need the enumerator - Guid IID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID; + Guid iidIAudioSessionManager2 = typeof(IAudioSessionManager2).GUID; object o; - speakers.Activate(ref IID_IAudioSessionManager2, 0, IntPtr.Zero, out o); + speakers.Activate(ref iidIAudioSessionManager2, 0, IntPtr.Zero, out o); IAudioSessionManager2 mgr = (IAudioSessionManager2)o; // enumerate sessions for on this device @@ -121,7 +117,7 @@ namespace SpotifyAPI.Local if (cpid == pid) { - volumeControl = ctl as ISimpleAudioVolume; + volumeControl = (ISimpleAudioVolume) ctl; break; } Marshal.ReleaseComObject(ctl); @@ -142,31 +138,31 @@ namespace SpotifyAPI.Local private enum EDataFlow { - eRender, - eCapture, - eAll, - EDataFlow_enum_count + ERender, + ECapture, + EAll, + EDataFlowEnumCount } private enum ERole { - eConsole, - eMultimedia, - eCommunications, - ERole_enum_count + EConsole, + EMultimedia, + ECommunications, + ERoleEnumCount } [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IMMDeviceEnumerator + private interface IMmDeviceEnumerator { int NotImpl1(); [PreserveSig] - int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMMDevice ppDevice); + int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMmDevice ppDevice); } [Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IMMDevice + private interface IMmDevice { [PreserveSig] int Activate(ref Guid iid, int dwClsCtx, IntPtr pActivationParams, [MarshalAs(UnmanagedType.IUnknown)] out object ppInterface); @@ -180,30 +176,30 @@ namespace SpotifyAPI.Local int NotImpl2(); [PreserveSig] - int GetSessionEnumerator(out IAudioSessionEnumerator SessionEnum); + int GetSessionEnumerator(out IAudioSessionEnumerator sessionEnum); } [Guid("E2F5BB11-0570-40CA-ACDD-3AA01277DEE8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAudioSessionEnumerator { [PreserveSig] - int GetCount(out int SessionCount); + int GetCount(out int sessionCount); [PreserveSig] - int GetSession(int SessionCount, out IAudioSessionControl2 Session); + int GetSession(int sessionCount, out IAudioSessionControl2 session); } [Guid("87CE5498-68D6-44E5-9215-6DA47EF883D8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface ISimpleAudioVolume { [PreserveSig] - int SetMasterVolume(float fLevel, ref Guid EventContext); + int SetMasterVolume(float fLevel, ref Guid eventContext); [PreserveSig] int GetMasterVolume(out float pfLevel); [PreserveSig] - int SetMute(bool bMute, ref Guid EventContext); + int SetMute(bool bMute, ref Guid eventContext); [PreserveSig] int GetMute(out bool pbMute); @@ -219,19 +215,19 @@ namespace SpotifyAPI.Local int GetDisplayName([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal); [PreserveSig] - int SetDisplayName([MarshalAs(UnmanagedType.LPWStr)]string Value, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext); + int SetDisplayName([MarshalAs(UnmanagedType.LPWStr)]string value, [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext); [PreserveSig] int GetIconPath([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal); [PreserveSig] - int SetIconPath([MarshalAs(UnmanagedType.LPWStr)] string Value, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext); + int SetIconPath([MarshalAs(UnmanagedType.LPWStr)] string value, [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext); [PreserveSig] int GetGroupingParam(out Guid pRetVal); [PreserveSig] - int SetGroupingParam([MarshalAs(UnmanagedType.LPStruct)] Guid Override, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext); + int SetGroupingParam([MarshalAs(UnmanagedType.LPStruct)] Guid Override, [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext); [PreserveSig] int NotImpl1(); diff --git a/SpotifyAPI/Web/Auth/AutorizationCodeAuth.cs b/SpotifyAPI/Web/Auth/AutorizationCodeAuth.cs index 0be2c3ba..dbf98cbf 100644 --- a/SpotifyAPI/Web/Auth/AutorizationCodeAuth.cs +++ b/SpotifyAPI/Web/Auth/AutorizationCodeAuth.cs @@ -98,13 +98,12 @@ namespace SpotifyAPI.Web.Auth private void HttpServerOnOnAuth(AuthEventArgs e) { - if (OnResponseReceivedEvent != null) - OnResponseReceivedEvent(new AutorizationCodeAuthResponse() - { - Code = e.Code, - State = e.State, - Error = e.Error - }); + OnResponseReceivedEvent?.Invoke(new AutorizationCodeAuthResponse() + { + Code = e.Code, + State = e.State, + Error = e.Error + }); } /// diff --git a/SpotifyAPI/Web/Auth/ImplicitGrantAuth.cs b/SpotifyAPI/Web/Auth/ImplicitGrantAuth.cs index 922a9d68..90a7141b 100644 --- a/SpotifyAPI/Web/Auth/ImplicitGrantAuth.cs +++ b/SpotifyAPI/Web/Auth/ImplicitGrantAuth.cs @@ -56,14 +56,13 @@ namespace SpotifyAPI.Web.Auth private void HttpServerOnOnAuth(AuthEventArgs e) { - if (OnResponseReceivedEvent != null) - OnResponseReceivedEvent(new Token - { - AccessToken = e.Code, - TokenType = e.TokenType, - ExpiresIn = e.ExpiresIn, - Error = e.Error - }, e.State); + OnResponseReceivedEvent?.Invoke(new Token + { + AccessToken = e.Code, + TokenType = e.TokenType, + ExpiresIn = e.ExpiresIn, + Error = e.Error + }, e.State); } /// diff --git a/SpotifyAPI/Web/SimpleHttpServer.cs b/SpotifyAPI/Web/SimpleHttpServer.cs index 7dcc7a20..ec87a0a6 100644 --- a/SpotifyAPI/Web/SimpleHttpServer.cs +++ b/SpotifyAPI/Web/SimpleHttpServer.cs @@ -147,7 +147,7 @@ namespace SpotifyAPI.Web var contentLen = Convert.ToInt32(HttpHeaders["Content-Length"]); if (contentLen > MaxPostSize) { - throw new Exception(String.Format("POST Content-Length({0}) too big for this simple server", contentLen)); + throw new Exception($"POST Content-Length({contentLen}) too big for this simple server"); } byte[] buf = new byte[BufSize]; int toRead = contentLen; @@ -274,12 +274,11 @@ namespace SpotifyAPI.Web p.OutputStream.WriteLine("

Spotify Auth canceled!

"); t = new Thread(o => { - if (OnAuth != null) - OnAuth(new AuthEventArgs() - { - State = col.Get(1), - Error = col.Get(0), - }); + OnAuth?.Invoke(new AuthEventArgs() + { + State = col.Get(1), + Error = col.Get(0), + }); }); } else @@ -287,12 +286,11 @@ namespace SpotifyAPI.Web p.OutputStream.WriteLine("

Spotify Auth successful!

"); t = new Thread(o => { - if (OnAuth != null) - OnAuth(new AuthEventArgs() - { - Code = col.Get(0), - State = col.Get(1) - }); + OnAuth?.Invoke(new AuthEventArgs() + { + Code = col.Get(0), + State = col.Get(1) + }); }); } } @@ -318,12 +316,11 @@ namespace SpotifyAPI.Web p.OutputStream.WriteLine("

Spotify Auth canceled!

"); t = new Thread(o => { - if (OnAuth != null) - OnAuth(new AuthEventArgs() - { - Error = col.Get(0), - State = col.Get(1) - }); + OnAuth?.Invoke(new AuthEventArgs() + { + Error = col.Get(0), + State = col.Get(1) + }); }); } else @@ -331,14 +328,13 @@ namespace SpotifyAPI.Web p.OutputStream.WriteLine("

Spotify Auth successful!

"); t = new Thread(o => { - if (OnAuth != null) - OnAuth(new AuthEventArgs() - { - Code = col.Get(0), - TokenType = col.Get(1), - ExpiresIn = Convert.ToInt32(col.Get(2)), - State = col.Get(3) - }); + OnAuth?.Invoke(new AuthEventArgs() + { + Code = col.Get(0), + TokenType = col.Get(1), + ExpiresIn = Convert.ToInt32(col.Get(2)), + State = col.Get(3) + }); }); } } diff --git a/SpotifyAPI/Web/SpotifyWebAPI.cs b/SpotifyAPI/Web/SpotifyWebAPI.cs index 84a9e9bc..9d9f3168 100644 --- a/SpotifyAPI/Web/SpotifyWebAPI.cs +++ b/SpotifyAPI/Web/SpotifyWebAPI.cs @@ -35,7 +35,7 @@ namespace SpotifyAPI.Web public void Dispose() { WebClient.Dispose(); - GC.SuppressFinalize(this); + GC.SuppressFinalize(this); //TODO } #region Search