Mayor code cleanup

Add Argument*Exceptions now use proper nameof operators.

Added exception messages to quite a few Argument*Exceptions.

Fixed rethorwing to be proper syntax.

Added a ton of null checkes. (This is only a start, there are about 500 places that need proper null handling)

Added some TODOs to log certain exceptions.

Fix sln again.

Fixed all AssemblyInfo's and added proper copyright (where I could find them)

We live in *current year*.

Fixed the use of braces.

Fixed a ton of properties, and made a fair amount of functions static that should be and can be static.

Made more Methods that should be static static.

You can now use static to find bad functions!

Removed unused variable. And added one more proper XML comment.
This commit is contained in:
Erwin de Haan
2019-01-06 21:50:43 +01:00
parent 3d867c2c46
commit ec1f5dc317
334 changed files with 1632 additions and 2603 deletions

View File

@@ -33,10 +33,10 @@ namespace SocketHttpListener
_reason = len > 2
? GetUtf8String(data.SubArray (2, len - 2))
: String.Empty;
: string.Empty;
}
private string GetUtf8String(byte[] bytes)
private static string GetUtf8String(byte[] bytes)
{
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}

View File

@@ -149,7 +149,7 @@ namespace SocketHttpListener
internal static string CheckIfValidControlData(this byte[] data, string paramName)
{
return data.Length > 125
? String.Format("'{0}' length must be less.", paramName)
? string.Format("'{0}' length must be less.", paramName)
: null;
}
@@ -222,7 +222,7 @@ namespace SocketHttpListener
internal static bool EqualsWith(this int value, char c, Action<int> action)
{
if (value < 0 || value > 255)
throw new ArgumentOutOfRangeException("value");
throw new ArgumentOutOfRangeException(nameof(value));
action(value);
return value == c - 0;
@@ -248,7 +248,7 @@ namespace SocketHttpListener
? "WebSocket server got an internal error."
: code == CloseStatusCode.TlsHandshakeFailure
? "An error has occurred while handshaking."
: String.Empty;
: string.Empty;
}
internal static string GetNameInternal(this string nameAndValue, string separator)
@@ -329,7 +329,7 @@ namespace SocketHttpListener
{
return value.IsToken()
? value
: String.Format("\"{0}\"", value.Replace("\"", "\\\""));
: string.Format("\"{0}\"", value.Replace("\"", "\\\""));
}
internal static byte[] ReadBytes(this Stream stream, int length)
@@ -484,13 +484,13 @@ namespace SocketHttpListener
this CompressionMethod method, params string[] parameters)
{
if (method == CompressionMethod.None)
return String.Empty;
return string.Empty;
var m = String.Format("permessage-{0}", method.ToString().ToLower());
var m = string.Format("permessage-{0}", method.ToString().ToLower());
if (parameters == null || parameters.Length == 0)
return m;
return String.Format("{0}; {1}", m, parameters.ToString("; "));
return string.Format("{0}; {1}", m, parameters.ToString("; "));
}
internal static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
@@ -715,7 +715,7 @@ namespace SocketHttpListener
case 507: return "Insufficient Storage";
}
return String.Empty;
return string.Empty;
}
/// <summary>
@@ -855,7 +855,7 @@ namespace SocketHttpListener
public static byte[] ToHostOrder(this byte[] src, ByteOrder srcOrder)
{
if (src == null)
throw new ArgumentNullException("src");
throw new ArgumentNullException(nameof(src));
return src.Length > 1 && !srcOrder.IsHostOrder()
? src.Reverse()
@@ -886,14 +886,14 @@ namespace SocketHttpListener
public static string ToString<T>(this T[] array, string separator)
{
if (array == null)
throw new ArgumentNullException("array");
throw new ArgumentNullException(nameof(array));
var len = array.Length;
if (len == 0)
return String.Empty;
return string.Empty;
if (separator == null)
separator = String.Empty;
separator = string.Empty;
var buff = new StringBuilder(64);
(len - 1).Times(i => buff.AppendFormat("{0}{1}", array[i].ToString(), separator));

View File

@@ -49,7 +49,7 @@ namespace SocketHttpListener
return data != null && data.Length > 0
? getEncoding(_headers["Content-Type"]).GetString(data, 0, data.Length)
: String.Empty;
: string.Empty;
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
@@ -56,7 +56,7 @@ namespace SocketHttpListener
}
}
private CookieCollection GetCookies(QueryParamCollection headers, bool response)
private static CookieCollection GetCookies(QueryParamCollection headers, bool response)
{
var name = response ? "Set-Cookie" : "Cookie";
return headers == null || !headers.Contains(name)
@@ -156,4 +156,4 @@ namespace SocketHttpListener
#endregion
}
}
}

View File

@@ -85,7 +85,7 @@ namespace SocketHttpListener
private static string convertToString (Opcode opcode, byte [] data)
{
return data.Length == 0
? String.Empty
? string.Empty
: opcode == Opcode.Text
? Encoding.UTF8.GetString (data, 0, data.Length)
: opcode.ToString ();

View File

@@ -271,7 +271,7 @@ namespace SocketHttpListener.Net
{
if (_saved.Length > 0)
{
_chunkSize = Int32.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
_chunkSize = int.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
}
}
catch (Exception)
@@ -285,7 +285,7 @@ namespace SocketHttpListener.Net
_chunkRead = 0;
try
{
_chunkSize = Int32.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
_chunkSize = int.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
}
catch (Exception)
{

View File

@@ -36,7 +36,7 @@ namespace SocketHttpListener.Net
if (pair.StartsWith("version", StringComparison.OrdinalIgnoreCase))
{
if (cookie != null)
cookie.Version = Int32.Parse(pair.GetValueInternal("=").Trim('"'));
cookie.Version = int.Parse(pair.GetValueInternal("=").Trim('"'));
}
else if (pair.StartsWith("expires", StringComparison.OrdinalIgnoreCase))
{
@@ -58,7 +58,7 @@ namespace SocketHttpListener.Net
}
else if (pair.StartsWith("max-age", StringComparison.OrdinalIgnoreCase))
{
var max = Int32.Parse(pair.GetValueInternal("=").Trim('"'));
var max = int.Parse(pair.GetValueInternal("=").Trim('"'));
var expires = DateTime.Now.AddSeconds((double)max);
if (cookie != null)
cookie.Expires = expires;
@@ -113,7 +113,7 @@ namespace SocketHttpListener.Net
cookies.Add(cookie);
string name;
string val = String.Empty;
string val = string.Empty;
var pos = pair.IndexOf('=');
if (pos == -1)

View File

@@ -168,6 +168,7 @@ namespace SocketHttpListener.Net
}
catch (ObjectDisposedException)
{
// TODO Investigate or properly fix.
}
catch (Exception ex)
{

View File

@@ -248,7 +248,7 @@ namespace SocketHttpListener.Net
internal void CheckDisposed()
{
if (disposed)
throw new ObjectDisposedException(GetType().ToString());
throw new ObjectDisposedException(GetType().Name);
}
internal void RegisterContext(HttpListenerContext context)

View File

@@ -26,7 +26,7 @@ namespace SocketHttpListener.Net
public GenericIdentity(string name)
{
if (name == null)
throw new System.ArgumentNullException("name");
throw new System.ArgumentNullException(nameof(name));
m_name = name;
m_type = "";
@@ -35,9 +35,9 @@ namespace SocketHttpListener.Net
public GenericIdentity(string name, string type)
{
if (name == null)
throw new System.ArgumentNullException("name");
throw new System.ArgumentNullException(nameof(name));
if (type == null)
throw new System.ArgumentNullException("type");
throw new System.ArgumentNullException(nameof(type));
m_name = name;
m_type = type;

View File

@@ -49,7 +49,7 @@ namespace SocketHttpListener.Net
public GenericPrincipal(IIdentity identity, string[] roles)
{
if (identity == null)
throw new ArgumentNullException("identity");
throw new ArgumentNullException(nameof(identity));
m_identity = identity;
if (roles != null)
@@ -81,7 +81,7 @@ namespace SocketHttpListener.Net
for (int i = 0; i < m_roles.Length; ++i)
{
if (m_roles[i] != null && String.Compare(m_roles[i], role, StringComparison.OrdinalIgnoreCase) == 0)
if (m_roles[i] != null && string.Compare(m_roles[i], role, StringComparison.OrdinalIgnoreCase) == 0)
return true;
}
return false;

View File

@@ -85,7 +85,7 @@ namespace SocketHttpListener.Net
{
listener.CheckDisposed();
if (uriPrefix == null)
throw new ArgumentNullException("uriPrefix");
throw new ArgumentNullException(nameof(uriPrefix));
bool result = prefixes.Remove(uriPrefix);
if (result && listener.IsListening)

View File

@@ -183,14 +183,14 @@ namespace SocketHttpListener.Net
}
}
if (String.Compare(Headers[HttpKnownHeaderNames.Expect], "100-continue", StringComparison.OrdinalIgnoreCase) == 0)
if (string.Compare(Headers[HttpKnownHeaderNames.Expect], "100-continue", StringComparison.OrdinalIgnoreCase) == 0)
{
HttpResponseStream output = _context.Connection.GetResponseStream();
output.InternalWrite(s_100continue, 0, s_100continue.Length);
}
}
internal static string Unquote(String str)
internal static string Unquote(string str)
{
int start = str.IndexOf('\"');
int end = str.LastIndexOf('\"');

View File

@@ -27,7 +27,7 @@ namespace SocketHttpListener.Net
public string[] UserLanguages => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.AcceptLanguage]);
private CookieCollection ParseCookies(Uri uri, string setCookieHeader)
private static CookieCollection ParseCookies(Uri uri, string setCookieHeader)
{
CookieCollection cookies = new CookieCollection();
return cookies;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
@@ -71,7 +71,7 @@ namespace SocketHttpListener.Net
public bool SendChunked
{
get { return EntitySendFormat == EntitySendFormat.Chunked; ; }
get { return EntitySendFormat == EntitySendFormat.Chunked; }
set { EntitySendFormat = value ? EntitySendFormat.Chunked : EntitySendFormat.ContentLength; }
}
@@ -104,7 +104,7 @@ namespace SocketHttpListener.Net
}
else
{
throw new ArgumentOutOfRangeException("net_clsmall");
throw new ArgumentOutOfRangeException(nameof(value));
}
}
}

View File

@@ -157,7 +157,7 @@ namespace SocketHttpListener.Net
private static byte[] s_crlf = new byte[] { 13, 10 };
private static byte[] GetChunkSizeBytes(int size, bool final)
{
string str = String.Format("{0:x}\r\n{1}", size, final ? "\r\n" : "");
string str = string.Format("{0:x}\r\n{1}", size, final ? "\r\n" : "");
return Encoding.ASCII.GetBytes(str);
}

View File

@@ -93,10 +93,10 @@ namespace SocketHttpListener.Net
public void Add(string header)
{
if (header == null)
throw new ArgumentNullException("header");
throw new ArgumentNullException(nameof(header));
int pos = header.IndexOf(':');
if (pos == -1)
throw new ArgumentException("no colon found", "header");
throw new ArgumentException("no colon found", nameof(header));
this.Add(header.Substring(0, pos), header.Substring(pos + 1));
}
@@ -104,7 +104,7 @@ namespace SocketHttpListener.Net
public override void Add(string name, string value)
{
if (name == null)
throw new ArgumentNullException("name");
throw new ArgumentNullException(nameof(name));
this.AddWithoutValidate(name, value);
}
@@ -112,13 +112,13 @@ namespace SocketHttpListener.Net
protected void AddWithoutValidate(string headerName, string headerValue)
{
if (!IsHeaderName(headerName))
throw new ArgumentException("invalid header name: " + headerName, "headerName");
throw new ArgumentException("invalid header name: " + headerName, nameof(headerName));
if (headerValue == null)
headerValue = String.Empty;
headerValue = string.Empty;
else
headerValue = headerValue.Trim();
if (!IsHeaderValue(headerValue))
throw new ArgumentException("invalid header value: " + headerValue, "headerValue");
throw new ArgumentException("invalid header value: " + headerValue, nameof(headerValue));
AddValue(headerName, headerValue);
}
@@ -131,7 +131,7 @@ namespace SocketHttpListener.Net
internal List<string> GetValues_internal(string header, bool split)
{
if (header == null)
throw new ArgumentNullException("header");
throw new ArgumentNullException(nameof(header));
var values = base.GetValues(header);
if (values == null || values.Count == 0)
@@ -205,10 +205,10 @@ namespace SocketHttpListener.Net
public static bool IsRestricted(string headerName, bool response)
{
if (headerName == null)
throw new ArgumentNullException("headerName");
throw new ArgumentNullException(nameof(headerName));
if (headerName.Length == 0)
throw new ArgumentException("empty string", "headerName");
throw new ArgumentException("empty string", nameof(headerName));
if (!IsHeaderName(headerName))
throw new ArgumentException("Invalid character in header");
@@ -224,11 +224,11 @@ namespace SocketHttpListener.Net
public override void Set(string name, string value)
{
if (name == null)
throw new ArgumentNullException("name");
throw new ArgumentNullException(nameof(name));
if (!IsHeaderName(name))
throw new ArgumentException("invalid header name");
if (value == null)
value = String.Empty;
value = string.Empty;
else
value = value.Trim();
if (!IsHeaderValue(value))
@@ -288,7 +288,7 @@ namespace SocketHttpListener.Net
{
int pos = header.IndexOf(':');
if (pos == -1)
throw new ArgumentException("no colon found", "header");
throw new ArgumentException("no colon found", nameof(header));
SetInternal(header.Substring(0, pos), header.Substring(pos + 1));
}
@@ -296,7 +296,7 @@ namespace SocketHttpListener.Net
internal void SetInternal(string name, string value)
{
if (value == null)
value = String.Empty;
value = string.Empty;
else
value = value.Trim();
if (!IsHeaderValue(value))

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics.CodeAnalysis;
@@ -86,27 +86,27 @@ namespace SocketHttpListener.Net.WebSockets
if (receiveBufferSize < MinReceiveBufferSize)
{
throw new ArgumentOutOfRangeException("net_WebSockets_ArgumentOutOfRange_TooSmall");
throw new ArgumentOutOfRangeException(nameof(receiveBufferSize), "The receiveBufferSize was too small.");
}
if (sendBufferSize < MinSendBufferSize)
{
throw new ArgumentOutOfRangeException("net_WebSockets_ArgumentOutOfRange_TooSmall");
throw new ArgumentOutOfRangeException(nameof(sendBufferSize), "The sendBufferSize was too small.");
}
if (receiveBufferSize > MaxBufferSize)
{
throw new ArgumentOutOfRangeException("net_WebSockets_ArgumentOutOfRange_TooBig");
throw new ArgumentOutOfRangeException(nameof(receiveBufferSize), "The receiveBufferSize was too large.");
}
if (sendBufferSize > MaxBufferSize)
{
throw new ArgumentOutOfRangeException("net_WebSockets_ArgumentOutOfRange_TooBig");
throw new ArgumentOutOfRangeException(nameof(sendBufferSize), "The sendBufferSize was too large.");
}
if (keepAliveInterval < Timeout.InfiniteTimeSpan) // -1 millisecond
{
throw new ArgumentOutOfRangeException("net_WebSockets_ArgumentOutOfRange_TooSmall");
throw new ArgumentOutOfRangeException(nameof(keepAliveInterval), "The keepAliveInterval was too small.");
}
}

View File

@@ -1,5 +1,5 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
@@ -8,27 +8,14 @@ using System.Runtime.InteropServices;
[assembly: AssemblyTitle("SocketHttpListener")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SocketHttpListener")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyCompany("Jellyfin Project")]
[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1d74413b-e7cf-455b-b021-f52bdf881542")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

View File

@@ -740,7 +740,7 @@ namespace SocketHttpListener
{
if (data == null)
{
throw new ArgumentNullException("data");
throw new ArgumentNullException(nameof(data));
}
var msg = _readyState.CheckIfOpen();
@@ -765,7 +765,7 @@ namespace SocketHttpListener
{
if (data == null)
{
throw new ArgumentNullException("data");
throw new ArgumentNullException(nameof(data));
}
var msg = _readyState.CheckIfOpen();