diff --git a/Directory.Build.props b/Directory.Build.props index 5f46ae2..3a817b2 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -5,6 +5,7 @@ disable disable latest-minimum + true en diff --git a/WaveBox.Core/src/BaseClasses.cs b/WaveBox.Core/src/BaseClasses.cs index 2e67a64..fd03290 100644 --- a/WaveBox.Core/src/BaseClasses.cs +++ b/WaveBox.Core/src/BaseClasses.cs @@ -197,7 +197,7 @@ public static string QueryText(this InsertType insertType) { case InsertType.Replace: return "REPLACE"; default: - throw new ArgumentOutOfRangeException("InsertType"); + throw new ArgumentOutOfRangeException(nameof(insertType)); } } } diff --git a/WaveBox.Core/src/Extensions/IListExtensions.cs b/WaveBox.Core/src/Extensions/IListExtensions.cs index 83dd0d9..37be730 100644 --- a/WaveBox.Core/src/Extensions/IListExtensions.cs +++ b/WaveBox.Core/src/Extensions/IListExtensions.cs @@ -65,7 +65,7 @@ public static string ToCSV(this IList list, bool quoted = false) { } } - return buffer.Trim(new char[] {' ', ','}); + return buffer.Trim(' ', ','); } } } diff --git a/WaveBox.Core/src/Logging/Log.cs b/WaveBox.Core/src/Logging/Log.cs index 5e75dbe..3999f97 100644 --- a/WaveBox.Core/src/Logging/Log.cs +++ b/WaveBox.Core/src/Logging/Log.cs @@ -72,7 +72,9 @@ private Microsoft.Extensions.Logging.ILogger Logger { private void Write(LogLevel level, object message, Exception exception) { Microsoft.Extensions.Logging.ILogger current = Logger; if (current != null) { - current.Log(level, exception, "{Message}", message); + if (current.IsEnabled(level)) { + current.Log(level, exception, "{Message}", message); + } } else { // Host not built yet; write straight to the console so early startup isn't silent Console.WriteLine(DateTime.Now.ToString("HH:mm:ss,fff") + " " + level + " " + category + " - " + message + (exception != null ? Environment.NewLine + exception : "")); diff --git a/WaveBox.Core/src/Model/Folder.cs b/WaveBox.Core/src/Model/Folder.cs index 228a2a7..6db92e2 100644 --- a/WaveBox.Core/src/Model/Folder.cs +++ b/WaveBox.Core/src/Model/Folder.cs @@ -54,7 +54,7 @@ public Folder ParentFolder() { return Injection.Get().FolderForId((int)ParentFolderId); } - public void Scan() { + public static void Scan() { // TO DO: scanning! yay! } diff --git a/WaveBox.Core/src/Model/Playlist.cs b/WaveBox.Core/src/Model/Playlist.cs index 08ebc65..3bcc288 100644 --- a/WaveBox.Core/src/Model/Playlist.cs +++ b/WaveBox.Core/src/Model/Playlist.cs @@ -61,7 +61,7 @@ public string CalculateHash() { foreach (PlaylistItem playlistItem in result) { itemIds.Append(playlistItem.ItemId); - itemIds.Append("|"); + itemIds.Append('|'); } } catch (Exception e) { logger.Error(e); @@ -152,9 +152,9 @@ public IList ListOfMediaItems() { conn = Injection.Get().GetSqliteConnection(); var result = conn.DeferredQuery("SELECT * FROM PlaylistItem WHERE PlaylistId = ? ORDER BY ItemPosition", PlaylistId); - IList items = new List(); + List items = new List(); foreach (PlaylistItem playlistItem in result) { - if (!ReferenceEquals(playlistItem.ItemId, null)) { + if (playlistItem.ItemId != null) { IMediaItem item = Injection.Get().MediaItemForId((int)playlistItem.ItemId); if (!ReferenceEquals(item, null)) { items.Add(item); @@ -177,7 +177,7 @@ public void RemoveMediaItem(IMediaItem item) { } public void RemoveMediaItems(IList items) { - IList indexes = new List(); + List indexes = new List(); if (PlaylistId == 0 || items == null) { return; } @@ -356,7 +356,7 @@ public void AddMediaItem(int itemId, bool updateDatabase = true) { } public void AddMediaItems(IList itemIds) { - IList items = new List(); + List items = new List(); foreach (int itemId in itemIds) { logger.IfInfo("Checking item id " + itemId); IMediaItem item = Injection.Get().MediaItemForId(itemId); @@ -376,7 +376,7 @@ public void InsertMediaItem(int itemId, int index) { public void InsertMediaItem(IMediaItem item, int index) { // make sure the input is within bounds and is not null - if (ReferenceEquals(item, null) || index > PlaylistCount || index < 0 || ReferenceEquals(PlaylistId, null)) { + if (ReferenceEquals(item, null) || index > PlaylistCount || index < 0 || PlaylistId == null) { return; } @@ -384,7 +384,7 @@ public void InsertMediaItem(IMediaItem item, int index) { try { int? id = Injection.Get().GenerateItemId(ItemType.PlaylistItem); - if (!ReferenceEquals(id, null)) { + if (id != null) { // to do - better way of knowing whether or not a query has been successfully completed. conn = Injection.Get().GetSqliteConnection(); conn.BeginTransaction(); @@ -446,13 +446,13 @@ public void ClearPlaylist() { } public void CreatePlaylist() { - if (ReferenceEquals(PlaylistId, null)) { + if (PlaylistId == null) { UpdateDatabase(); } } public void DeletePlaylist() { - if (ReferenceEquals(PlaylistId, null)) { + if (PlaylistId == null) { return; } diff --git a/WaveBox.Core/src/Model/User.cs b/WaveBox.Core/src/Model/User.cs index f8fac5f..349f78b 100644 --- a/WaveBox.Core/src/Model/User.cs +++ b/WaveBox.Core/src/Model/User.cs @@ -60,7 +60,7 @@ public bool HasPermission(Role role) { return this.Role >= role ? true : false; } - public bool UpdateSession(string sessionId) { + public static bool UpdateSession(string sessionId) { // Update user's session based on its session ID Session s = Injection.Get().SessionForSessionId(sessionId); @@ -224,7 +224,7 @@ public bool CreateSession(string password, string clientName) { } public bool Delete() { - if (ReferenceEquals(UserId, null)) { + if (UserId == null) { return true; } diff --git a/WaveBox.Core/src/Repository/AlbumArtistRepository.cs b/WaveBox.Core/src/Repository/AlbumArtistRepository.cs index c3a1d93..07c2797 100644 --- a/WaveBox.Core/src/Repository/AlbumArtistRepository.cs +++ b/WaveBox.Core/src/Repository/AlbumArtistRepository.cs @@ -14,15 +14,9 @@ public class AlbumArtistRepository : IAlbumArtistRepository { private readonly ISongRepository songRepository; public AlbumArtistRepository(IDatabase database, IItemRepository itemRepository, ISongRepository songRepository) { - if (database == null) { - throw new ArgumentNullException("database"); - } - if (itemRepository == null) { - throw new ArgumentNullException("itemRepository"); - } - if (songRepository == null) { - throw new ArgumentNullException("songRepository"); - } + ArgumentNullException.ThrowIfNull(database); + ArgumentNullException.ThrowIfNull(itemRepository); + ArgumentNullException.ThrowIfNull(songRepository); this.database = database; this.itemRepository = itemRepository; @@ -156,11 +150,11 @@ public IList SinglesForAlbumArtistId(int albumArtistId) { try { conn = database.GetSqliteConnection(); - IList songs; + List songs; songs = conn.Query("SELECT ItemId FROM Song WHERE AlbumArtistId = ? AND AlbumId IS NULL", albumArtistId); if (songs.Count > 0) { - IList songIds = new List(); + List songIds = new List(); foreach (Song song in songs) { songIds.Add((int)song.ItemId); } diff --git a/WaveBox.Core/src/Repository/AlbumRepository.cs b/WaveBox.Core/src/Repository/AlbumRepository.cs index 9b84985..f3b3e11 100644 --- a/WaveBox.Core/src/Repository/AlbumRepository.cs +++ b/WaveBox.Core/src/Repository/AlbumRepository.cs @@ -14,12 +14,8 @@ public class AlbumRepository : IAlbumRepository { private readonly IItemRepository itemRepository; public AlbumRepository(IDatabase database, IItemRepository itemRepository) { - if (database == null) { - throw new ArgumentNullException("database"); - } - if (itemRepository == null) { - throw new ArgumentNullException("itemRepository"); - } + ArgumentNullException.ThrowIfNull(database); + ArgumentNullException.ThrowIfNull(itemRepository); this.database = database; this.itemRepository = itemRepository; diff --git a/WaveBox.Core/src/Repository/ArtRepository.cs b/WaveBox.Core/src/Repository/ArtRepository.cs index 9cbb8bc..a94356e 100644 --- a/WaveBox.Core/src/Repository/ArtRepository.cs +++ b/WaveBox.Core/src/Repository/ArtRepository.cs @@ -9,9 +9,7 @@ public class ArtRepository : IArtRepository { private readonly IDatabase database; public ArtRepository(IDatabase database) { - if (database == null) { - throw new ArgumentNullException("database"); - } + ArgumentNullException.ThrowIfNull(database); this.database = database; } diff --git a/WaveBox.Core/src/Repository/ArtistRepository.cs b/WaveBox.Core/src/Repository/ArtistRepository.cs index 1481986..d4efe45 100644 --- a/WaveBox.Core/src/Repository/ArtistRepository.cs +++ b/WaveBox.Core/src/Repository/ArtistRepository.cs @@ -13,12 +13,8 @@ public class ArtistRepository : IArtistRepository { private readonly IItemRepository itemRepository; public ArtistRepository(IDatabase database, IItemRepository itemRepository) { - if (database == null) { - throw new ArgumentNullException("database"); - } - if (itemRepository == null) { - throw new ArgumentNullException("itemRepository"); - } + ArgumentNullException.ThrowIfNull(database); + ArgumentNullException.ThrowIfNull(itemRepository); this.database = database; this.itemRepository = itemRepository; diff --git a/WaveBox.Core/src/Repository/FavoriteRepository.cs b/WaveBox.Core/src/Repository/FavoriteRepository.cs index 5ae74e9..f2560ba 100644 --- a/WaveBox.Core/src/Repository/FavoriteRepository.cs +++ b/WaveBox.Core/src/Repository/FavoriteRepository.cs @@ -19,36 +19,16 @@ public class FavoriteRepository : IFavoriteRepository { private readonly IItemRepository itemRepository; public FavoriteRepository(IDatabase database, IAlbumArtistRepository albumArtistRepository, IAlbumRepository albumRepository, IArtistRepository artistRepository, IFolderRepository folderRepository, IGenreRepository genreRepository, IPlaylistRepository playlistRepository, ISongRepository songRepository, IVideoRepository videoRepository, IItemRepository itemRepository) { - if (database == null) { - throw new ArgumentNullException("database"); - } - if (albumRepository == null) { - throw new ArgumentNullException("albumRepository"); - } - if (albumArtistRepository == null) { - throw new ArgumentNullException("albumArtistRepository"); - } - if (artistRepository == null) { - throw new ArgumentNullException("artistRepository"); - } - if (folderRepository == null) { - throw new ArgumentNullException("folderRepository"); - } - if (genreRepository == null) { - throw new ArgumentNullException("genreRepository"); - } - if (playlistRepository == null) { - throw new ArgumentNullException("playlistRepository"); - } - if (songRepository == null) { - throw new ArgumentNullException("songRepository"); - } - if (videoRepository == null) { - throw new ArgumentNullException("videoRepository"); - } - if (itemRepository == null) { - throw new ArgumentNullException("itemRepository"); - } + ArgumentNullException.ThrowIfNull(database); + ArgumentNullException.ThrowIfNull(albumRepository); + ArgumentNullException.ThrowIfNull(albumArtistRepository); + ArgumentNullException.ThrowIfNull(artistRepository); + ArgumentNullException.ThrowIfNull(folderRepository); + ArgumentNullException.ThrowIfNull(genreRepository); + ArgumentNullException.ThrowIfNull(playlistRepository); + ArgumentNullException.ThrowIfNull(songRepository); + ArgumentNullException.ThrowIfNull(videoRepository); + ArgumentNullException.ThrowIfNull(itemRepository); this.database = database; this.albumArtistRepository = albumArtistRepository; @@ -94,9 +74,10 @@ public IList FavoritesForUserId(int userId) { public IList FavoritesForArtistId(int? artistId, int? userId) { if (artistId == null) { - throw new ArgumentNullException("artistId"); - } else if (userId == null) { - throw new ArgumentNullException("userId"); + throw new ArgumentNullException(nameof(artistId)); + } + if (userId == null) { + throw new ArgumentNullException(nameof(userId)); } return this.database.GetList("SELECT * FROM Favorite LEFT JOIN Song ON Song.ItemId = Favorite.FavoriteItemId WHERE Song.ArtistId = ? AND Favorite.FavoriteUserId = ?", artistId, userId); @@ -104,9 +85,10 @@ public IList FavoritesForArtistId(int? artistId, int? userId) { public IList FavoritesForAlbumArtistId(int? albumArtistId, int? userId) { if (albumArtistId == null) { - throw new ArgumentNullException("artistId"); - } else if (userId == null) { - throw new ArgumentNullException("userId"); + throw new ArgumentNullException(nameof(albumArtistId)); + } + if (userId == null) { + throw new ArgumentNullException(nameof(userId)); } return this.database.GetList("SELECT * FROM Favorite LEFT JOIN Song ON Song.ItemId = Favorite.FavoriteItemId WHERE Song.AlbumArtistId = ? AND Favorite.FavoriteUserId = ?", albumArtistId, userId); @@ -117,7 +99,7 @@ public IList ItemsForFavorites(IList favorites) { return null; } - IList items = new List(); + List items = new List(); foreach (Favorite fav in favorites) { switch (fav.FavoriteItemType) { case ItemType.AlbumArtist: diff --git a/WaveBox.Core/src/Repository/FolderRepository.cs b/WaveBox.Core/src/Repository/FolderRepository.cs index d43629d..82b0e9a 100644 --- a/WaveBox.Core/src/Repository/FolderRepository.cs +++ b/WaveBox.Core/src/Repository/FolderRepository.cs @@ -15,18 +15,10 @@ public class FolderRepository : IFolderRepository { private readonly IVideoRepository videoRepository; public FolderRepository(IDatabase database, IServerSettings serverSettings, ISongRepository songRepository, IVideoRepository videoRepository) { - if (database == null) { - throw new ArgumentNullException("database"); - } - if (serverSettings == null) { - throw new ArgumentNullException("serverSettings"); - } - if (songRepository == null) { - throw new ArgumentNullException("songRepository"); - } - if (videoRepository == null) { - throw new ArgumentNullException("videoRepository"); - } + ArgumentNullException.ThrowIfNull(database); + ArgumentNullException.ThrowIfNull(serverSettings); + ArgumentNullException.ThrowIfNull(songRepository); + ArgumentNullException.ThrowIfNull(videoRepository); this.database = database; this.serverSettings = serverSettings; diff --git a/WaveBox.Core/src/Repository/GenreRepository.cs b/WaveBox.Core/src/Repository/GenreRepository.cs index 407c305..a73cb2b 100644 --- a/WaveBox.Core/src/Repository/GenreRepository.cs +++ b/WaveBox.Core/src/Repository/GenreRepository.cs @@ -12,9 +12,7 @@ public class GenreRepository : IGenreRepository { private readonly IDatabase database; public GenreRepository(IDatabase database) { - if (database == null) { - throw new ArgumentNullException("database"); - } + ArgumentNullException.ThrowIfNull(database); this.database = database; } diff --git a/WaveBox.Core/src/Repository/ItemRepository.cs b/WaveBox.Core/src/Repository/ItemRepository.cs index f14af8a..bcaad36 100644 --- a/WaveBox.Core/src/Repository/ItemRepository.cs +++ b/WaveBox.Core/src/Repository/ItemRepository.cs @@ -15,9 +15,7 @@ public class ItemRepository : IItemRepository { private readonly IDatabase database; public ItemRepository(IDatabase database) { - if (database == null) { - throw new ArgumentNullException("database"); - } + ArgumentNullException.ThrowIfNull(database); this.database = database; } diff --git a/WaveBox.Core/src/Repository/MediaItemRepository.cs b/WaveBox.Core/src/Repository/MediaItemRepository.cs index 908f38f..08a9c77 100644 --- a/WaveBox.Core/src/Repository/MediaItemRepository.cs +++ b/WaveBox.Core/src/Repository/MediaItemRepository.cs @@ -7,15 +7,9 @@ public class MediaItemRepository : IMediaItemRepository { private readonly IVideoRepository videoRepository; public MediaItemRepository(IItemRepository itemRepository, ISongRepository songRepository, IVideoRepository videoRepository) { - if (itemRepository == null) { - throw new ArgumentNullException("itemRepository"); - } - if (songRepository == null) { - throw new ArgumentNullException("songRepository"); - } - if (videoRepository == null) { - throw new ArgumentNullException("videoRepository"); - } + ArgumentNullException.ThrowIfNull(itemRepository); + ArgumentNullException.ThrowIfNull(songRepository); + ArgumentNullException.ThrowIfNull(videoRepository); this.itemRepository = itemRepository; this.songRepository = songRepository; diff --git a/WaveBox.Core/src/Repository/PlaylistRepository.cs b/WaveBox.Core/src/Repository/PlaylistRepository.cs index d9c6106..a54a38c 100644 --- a/WaveBox.Core/src/Repository/PlaylistRepository.cs +++ b/WaveBox.Core/src/Repository/PlaylistRepository.cs @@ -10,9 +10,7 @@ public class PlaylistRepository : IPlaylistRepository { private readonly IDatabase database; public PlaylistRepository(IDatabase database) { - if (database == null) { - throw new ArgumentNullException("database"); - } + ArgumentNullException.ThrowIfNull(database); this.database = database; } diff --git a/WaveBox.Core/src/Repository/SessionRepository.cs b/WaveBox.Core/src/Repository/SessionRepository.cs index b024ffb..f039e41 100644 --- a/WaveBox.Core/src/Repository/SessionRepository.cs +++ b/WaveBox.Core/src/Repository/SessionRepository.cs @@ -11,12 +11,10 @@ public class SessionRepository : ISessionRepository { private readonly IDatabase database; - private IDictionary Sessions { get; set; } + private Dictionary Sessions { get; set; } public SessionRepository(IDatabase database) { - if (database == null) { - throw new ArgumentNullException("database"); - } + ArgumentNullException.ThrowIfNull(database); this.database = database; @@ -42,8 +40,8 @@ public Session SessionForRowId(int rowId) { public Session SessionForSessionId(string sessionId) { lock (this.Sessions) { - if (this.Sessions.ContainsKey(sessionId)) { - return this.Sessions[sessionId]; + if (this.Sessions.TryGetValue(sessionId, out Session session)) { + return session; } return null; @@ -147,8 +145,8 @@ public bool DeleteSessionsForUserId(int userId) { } lock (this.Sessions) { - if (this.Sessions.ContainsKey(sessionId)) { - return this.Sessions[sessionId].UserId; + if (this.Sessions.TryGetValue(sessionId, out Session session)) { + return session.UserId; } return null; diff --git a/WaveBox.Core/src/Repository/SongRepository.cs b/WaveBox.Core/src/Repository/SongRepository.cs index fead699..e0352f1 100644 --- a/WaveBox.Core/src/Repository/SongRepository.cs +++ b/WaveBox.Core/src/Repository/SongRepository.cs @@ -13,9 +13,7 @@ public class SongRepository : ISongRepository { private readonly IDatabase database; public SongRepository(IDatabase database) { - if (database == null) { - throw new ArgumentNullException("database"); - } + ArgumentNullException.ThrowIfNull(database); this.database = database; } diff --git a/WaveBox.Core/src/Repository/StatRepository.cs b/WaveBox.Core/src/Repository/StatRepository.cs index 5f0f5f4..956be46 100644 --- a/WaveBox.Core/src/Repository/StatRepository.cs +++ b/WaveBox.Core/src/Repository/StatRepository.cs @@ -9,9 +9,7 @@ public class StatRepository : IStatRepository { private readonly IDatabase database; public StatRepository(IDatabase database) { - if (database == null) { - throw new ArgumentNullException("database"); - } + ArgumentNullException.ThrowIfNull(database); this.database = database; } diff --git a/WaveBox.Core/src/Repository/UserRepository.cs b/WaveBox.Core/src/Repository/UserRepository.cs index a5777d6..1cba38a 100644 --- a/WaveBox.Core/src/Repository/UserRepository.cs +++ b/WaveBox.Core/src/Repository/UserRepository.cs @@ -15,12 +15,8 @@ public class UserRepository : IUserRepository { private IDictionary Users { get; set; } public UserRepository(IDatabase database, IItemRepository itemRepository) { - if (database == null) { - throw new ArgumentNullException("database"); - } - if (itemRepository == null) { - throw new ArgumentNullException("itemRepository"); - } + ArgumentNullException.ThrowIfNull(database); + ArgumentNullException.ThrowIfNull(itemRepository); this.database = database; this.itemRepository = itemRepository; @@ -48,8 +44,8 @@ private bool ReloadUsers() { public User UserForId(int userId) { lock (this.Users) { - if (this.Users.ContainsKey(userId)) { - return this.Users[userId]; + if (this.Users.TryGetValue(userId, out User user)) { + return user; } return new User() { UserId = userId }; @@ -101,7 +97,7 @@ public User CreateUser(string userName, string password, Role role, long? delete public User CreateTestUser(long? durationSeconds) { // Create a new user with random username and password, that lasts for the specified duration - if (ReferenceEquals(durationSeconds, null)) { + if (durationSeconds == null) { // If no duration specified, use 24 hours durationSeconds = 60 * 60 * 24; } diff --git a/WaveBox.Core/src/Repository/VideoRepository.cs b/WaveBox.Core/src/Repository/VideoRepository.cs index 3947464..fbe03cb 100644 --- a/WaveBox.Core/src/Repository/VideoRepository.cs +++ b/WaveBox.Core/src/Repository/VideoRepository.cs @@ -11,9 +11,7 @@ public class VideoRepository : IVideoRepository { private readonly IDatabase database; public VideoRepository(IDatabase database) { - if (database == null) { - throw new ArgumentNullException("database"); - } + ArgumentNullException.ThrowIfNull(database); this.database = database; } diff --git a/WaveBox.Core/src/SQLiteNet.cs b/WaveBox.Core/src/SQLiteNet.cs index fa642a1..1fca727 100644 --- a/WaveBox.Core/src/SQLiteNet.cs +++ b/WaveBox.Core/src/SQLiteNet.cs @@ -414,7 +414,7 @@ private struct IndexInfo { /// Executes a "drop table" on the database. This is non-recoverable. /// public int DropTable() { - var map = GetMapping(typeof (T), TableMappingType.Write); + var map = GetMapping(TableMappingType.Write); var query = string.Format("drop table if exists \"{0}\"", map.TableName); @@ -778,7 +778,7 @@ public IEnumerable DeferredQuery(ITableMapping map, string query, params /// if the object is not found. /// public T Get(object pk) where T : new() { - var map = GetMapping(typeof (T), TableMappingType.Read); + var map = GetMapping(TableMappingType.Read); return Query(map.GetByPrimaryKeySql, pk).First(); } @@ -810,7 +810,7 @@ public IEnumerable DeferredQuery(ITableMapping map, string query, params /// if the object is not found. /// public T Find(object pk) where T : new() { - var map = GetMapping(typeof (T), TableMappingType.Read); + var map = GetMapping(TableMappingType.Read); return Query(map.GetByPrimaryKeySql, pk).FirstOrDefault(); } @@ -996,7 +996,7 @@ private void DoSavePointExecute(string savepoint, string cmd) { int firstLen = savepoint.IndexOf('D'); if (firstLen >= 2 && savepoint.Length > firstLen + 1) { int depth; - if (Int32.TryParse(savepoint.Substring(firstLen + 1), out depth)) { + if (Int32.TryParse(savepoint.AsSpan(firstLen + 1), out depth)) { // TODO: Mild race here, but inescapable without locking almost everywhere. if (0 <= depth && depth < _trasactionDepth) { Volatile.Write(ref _trasactionDepth, depth); @@ -1006,8 +1006,8 @@ private void DoSavePointExecute(string savepoint, string cmd) { } } - throw new ArgumentException("savePoint", - "savePoint is not valid, and should be the result of a call to SaveTransactionPoint."); + throw new ArgumentException("savePoint is not valid, and should be the result of a call to SaveTransactionPoint.", + nameof(savepoint)); } /// @@ -1208,7 +1208,7 @@ public virtual int Delete(object objectToDelete) { /// The type of object. /// public int Delete(object primaryKey) { - var map = GetMapping(typeof (T), TableMappingType.Write); + var map = GetMapping(TableMappingType.Write); var pk = map.PK; if (pk == null) { throw new NotSupportedException("Cannot delete " + map.TableName + ": it has no PK"); @@ -1229,7 +1229,7 @@ public int Delete(object primaryKey) { /// The type of objects to delete. /// public int DeleteAll() { - var map = GetMapping(typeof (T), TableMappingType.Write); + var map = GetMapping(TableMappingType.Write); var query = string.Format("delete from \"{0}\"", map.TableName); return Execute(query); } @@ -1405,7 +1405,7 @@ public PreparedSqlLiteInsertCommand GetInsertCommand(SQLiteConnection conn, stri private PreparedSqlLiteInsertCommand CreateInsertCommand(SQLiteConnection conn, string extra, InsertType insertType) { var cols = InsertColumns; string insertSql; - if (!cols.Any() && Columns.Count() == 1 && Columns[0].IsAutoInc) { + if (cols.Length == 0 && Columns.Length == 1 && Columns[0].IsAutoInc) { insertSql = string.Format(insertType.QueryText() + " {1} INTO \"{0}\" DEFAULT VALUES", TableName, extra); } else { insertSql = string.Format(insertType.QueryText() + " {3} INTO \"{0}\"({1}) VALUES ({2})", TableName, @@ -1614,11 +1614,11 @@ public int ExecuteNonQuery() { } public IEnumerable ExecuteDeferredQuery() { - return ExecuteDeferredQuery(_conn.GetMapping(typeof (T), TableMappingType.Read)); + return ExecuteDeferredQuery(_conn.GetMapping(TableMappingType.Read)); } public List ExecuteQuery() { - return ExecuteDeferredQuery(_conn.GetMapping(typeof (T), TableMappingType.Read)).ToList(); + return ExecuteDeferredQuery(_conn.GetMapping(TableMappingType.Read)).ToList(); } public List ExecuteQuery(ITableMapping map) { @@ -1720,7 +1720,7 @@ private Sqlite3Statement Prepare() { return stmt; } - private void Finalize(Sqlite3Statement stmt) { + private static void Finalize(Sqlite3Statement stmt) { SQLite3.Finalize(stmt); } @@ -1741,35 +1741,35 @@ private void BindAll(Sqlite3Statement stmt) { internal static void BindParameter(Sqlite3Statement stmt, int index, object value, bool storeDateTimeAsTicks) { if (value == null) { - SQLite3.BindNull(stmt, index); + _ = SQLite3.BindNull(stmt, index); } else { if (value is Int32) { - SQLite3.BindInt(stmt, index, (int) value); + _ = SQLite3.BindInt(stmt, index, (int) value); } else if (value is String) { - SQLite3.BindText(stmt, index, (string) value, -1, NegativePointer); + _ = SQLite3.BindText(stmt, index, (string) value, -1, NegativePointer); } else if (value is Byte || value is UInt16 || value is SByte || value is Int16) { - SQLite3.BindInt(stmt, index, Convert.ToInt32(value)); + _ = SQLite3.BindInt(stmt, index, Convert.ToInt32(value)); } else if (value is Boolean) { - SQLite3.BindInt(stmt, index, (bool) value ? 1 : 0); + _ = SQLite3.BindInt(stmt, index, (bool) value ? 1 : 0); } else if (value is UInt32 || value is Int64) { - SQLite3.BindInt64(stmt, index, Convert.ToInt64(value)); + _ = SQLite3.BindInt64(stmt, index, Convert.ToInt64(value)); } else if (value is Single || value is Double || value is Decimal) { - SQLite3.BindDouble(stmt, index, Convert.ToDouble(value)); + _ = SQLite3.BindDouble(stmt, index, Convert.ToDouble(value)); } else if (value is DateTime) { if (storeDateTimeAsTicks) { - SQLite3.BindInt64(stmt, index, ((DateTime) value).Ticks); + _ = SQLite3.BindInt64(stmt, index, ((DateTime) value).Ticks); } else { - SQLite3.BindText(stmt, index, ((DateTime) value).ToString("yyyy-MM-dd HH:mm:ss"), -1, - NegativePointer); + _ = SQLite3.BindText(stmt, index, ((DateTime) value).ToString("yyyy-MM-dd HH:mm:ss"), -1, + NegativePointer); } #if !NETFX_CORE } else if (value.GetType().IsEnum) { #else } else if (value.GetType().GetTypeInfo().IsEnum) { #endif - SQLite3.BindInt(stmt, index, Convert.ToInt32(value)); + _ = SQLite3.BindInt(stmt, index, Convert.ToInt32(value)); } else if (value is byte[]) { - SQLite3.BindBlob(stmt, index, (byte[]) value, ((byte[]) value).Length, NegativePointer); + _ = SQLite3.BindBlob(stmt, index, (byte[]) value, ((byte[]) value).Length, NegativePointer); #if SQLITE_SUPPORT_GUID } else if (value is Guid) { SQLite3.BindText(stmt, index, ((Guid)value).ToString(), 72, NegativePointer); @@ -1846,7 +1846,7 @@ private object ReadCol(Sqlite3Statement stmt, int index, SQLite3.ColType type, T /// /// Since the insert never changed, we only need to prepare once. /// - public class PreparedSqlLiteInsertCommand : ISQLiteCommand { + public class PreparedSqlLiteInsertCommand : ISQLiteCommand, IDisposable { public bool Initialized { get; set; } protected SQLiteConnection Connection { get; set; } @@ -1957,7 +1957,7 @@ private TableQuery(SQLiteConnection conn, ITableMapping table) { public TableQuery(SQLiteConnection conn) { Connection = conn; - Table = Connection.GetMapping(typeof (T), TableMappingType.Read); + Table = Connection.GetMapping(TableMappingType.Read); } public TableQuery Clone() @@ -2060,7 +2060,7 @@ public TableQuery Join( Expression> resultSelector) where TInner : new() where TResult : new() { - var q = new TableQuery(Connection, Connection.GetMapping(typeof (TResult), TableMappingType.Read)) { + var q = new TableQuery(Connection, Connection.GetMapping(TableMappingType.Read)) { _joinOuter = this, _joinOuterKeySelector = outerKeySelector, _joinInner = inner, @@ -2235,15 +2235,15 @@ private CompileResult CompileExpr(Expression expr, List queryArgs) { // if (val != null && val is System.Collections.IEnumerable && !(val is string)) { var sb = new System.Text.StringBuilder(); - sb.Append("("); + sb.Append('('); var head = ""; foreach (var a in (System.Collections.IEnumerable) val) { queryArgs.Add(a); sb.Append(head); - sb.Append("?"); + sb.Append('?'); head = ","; } - sb.Append(")"); + sb.Append(')'); return new CompileResult { CommandText = sb.ToString(), Value = val @@ -2264,7 +2264,7 @@ private CompileResult CompileExpr(Expression expr, List queryArgs) { /// Compiles a BinaryExpression where one of the parameters is null. /// /// The non-null parameter - private string CompileNullBinaryExpression(BinaryExpression expression, CompileResult parameter) { + private static string CompileNullBinaryExpression(BinaryExpression expression, CompileResult parameter) { if (expression.NodeType == ExpressionType.Equal) { return "(" + parameter.CommandText + " is ?)"; } else if (expression.NodeType == ExpressionType.NotEqual) { @@ -2274,7 +2274,7 @@ private string CompileNullBinaryExpression(BinaryExpression expression, CompileR expression.NodeType.ToString()); } - private string GetSqlName(Expression expr) { + private static string GetSqlName(BinaryExpression expr) { var n = expr.NodeType; if (n == ExpressionType.GreaterThan) { return ">"; @@ -2368,33 +2368,36 @@ public enum ConfigOption { } #if !WINDOWS_PHONE - [DllImport("e_sqlite3", EntryPoint = "sqlite3_open", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Open([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db); + [DllImport("e_sqlite3", EntryPoint = "sqlite3_open", CallingConvention = CallingConvention.Cdecl, + BestFitMapping = false)] + internal static extern Result Open([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db); - [DllImport("e_sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Open([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db, int flags, + [DllImport("e_sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl, + BestFitMapping = false)] + internal static extern Result Open([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db, int flags, IntPtr zvfs); [DllImport("e_sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Open(byte[] filename, out IntPtr db, int flags, IntPtr zvfs); + internal static extern Result Open(byte[] filename, out IntPtr db, int flags, IntPtr zvfs); [DllImport("e_sqlite3", EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db); + internal static extern Result Open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db); [DllImport("e_sqlite3", EntryPoint = "sqlite3_close", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Close(IntPtr db); + internal static extern Result Close(IntPtr db); [DllImport("e_sqlite3", EntryPoint = "sqlite3_config", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Config(ConfigOption option); + internal static extern Result Config(ConfigOption option); [DllImport("e_sqlite3", EntryPoint = "sqlite3_busy_timeout", CallingConvention = CallingConvention.Cdecl)] - public static extern Result BusyTimeout(IntPtr db, int milliseconds); + internal static extern Result BusyTimeout(IntPtr db, int milliseconds); [DllImport("e_sqlite3", EntryPoint = "sqlite3_changes", CallingConvention = CallingConvention.Cdecl)] - public static extern int Changes(IntPtr db); + internal static extern int Changes(IntPtr db); - [DllImport("e_sqlite3", EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Prepare2(IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, int numBytes, + [DllImport("e_sqlite3", EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl, + BestFitMapping = false)] + internal static extern Result Prepare2(IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, int numBytes, out IntPtr stmt, IntPtr pzTail); public static IntPtr Prepare2(IntPtr db, string query) { @@ -2410,7 +2413,7 @@ public static IntPtr Prepare2(IntPtr db, string query) { // first statement of a script. This one hands back the pointer to the remaining SQL, // which is what lets ExecuteScript walk a multi-statement file. [DllImport("e_sqlite3", EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Prepare2(IntPtr db, IntPtr sql, int numBytes, + internal static extern Result Prepare2(IntPtr db, IntPtr sql, int numBytes, out IntPtr stmt, out IntPtr pzTail); /// @@ -2488,52 +2491,53 @@ private static string RemainingText(byte[] utf8, int offset) { } [DllImport("e_sqlite3", EntryPoint = "sqlite3_step", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Step(IntPtr stmt); + internal static extern Result Step(IntPtr stmt); [DllImport("e_sqlite3", EntryPoint = "sqlite3_reset", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Reset(IntPtr stmt); + internal static extern Result Reset(IntPtr stmt); [DllImport("e_sqlite3", EntryPoint = "sqlite3_finalize", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Finalize(IntPtr stmt); + internal static extern Result Finalize(IntPtr stmt); [DllImport("e_sqlite3", EntryPoint = "sqlite3_last_insert_rowid", CallingConvention = CallingConvention.Cdecl)] - public static extern long LastInsertRowid(IntPtr db); + internal static extern long LastInsertRowid(IntPtr db); [DllImport("e_sqlite3", EntryPoint = "sqlite3_errmsg16", CallingConvention = CallingConvention.Cdecl)] - public static extern IntPtr Errmsg(IntPtr db); + internal static extern IntPtr Errmsg(IntPtr db); public static string GetErrmsg(IntPtr db) { return Marshal.PtrToStringUni(Errmsg(db)); } - [DllImport("e_sqlite3", EntryPoint = "sqlite3_bind_parameter_index", CallingConvention = CallingConvention.Cdecl)] - public static extern int BindParameterIndex(IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name); + [DllImport("e_sqlite3", EntryPoint = "sqlite3_bind_parameter_index", CallingConvention = CallingConvention.Cdecl, + BestFitMapping = false)] + internal static extern int BindParameterIndex(IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name); [DllImport("e_sqlite3", EntryPoint = "sqlite3_bind_null", CallingConvention = CallingConvention.Cdecl)] - public static extern int BindNull(IntPtr stmt, int index); + internal static extern int BindNull(IntPtr stmt, int index); [DllImport("e_sqlite3", EntryPoint = "sqlite3_bind_int", CallingConvention = CallingConvention.Cdecl)] - public static extern int BindInt(IntPtr stmt, int index, int val); + internal static extern int BindInt(IntPtr stmt, int index, int val); [DllImport("e_sqlite3", EntryPoint = "sqlite3_bind_int64", CallingConvention = CallingConvention.Cdecl)] - public static extern int BindInt64(IntPtr stmt, int index, long val); + internal static extern int BindInt64(IntPtr stmt, int index, long val); [DllImport("e_sqlite3", EntryPoint = "sqlite3_bind_double", CallingConvention = CallingConvention.Cdecl)] - public static extern int BindDouble(IntPtr stmt, int index, double val); + internal static extern int BindDouble(IntPtr stmt, int index, double val); [DllImport("e_sqlite3", EntryPoint = "sqlite3_bind_text16", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] - public static extern int BindText(IntPtr stmt, int index, [MarshalAs(UnmanagedType.LPWStr)] string val, int n, + internal static extern int BindText(IntPtr stmt, int index, [MarshalAs(UnmanagedType.LPWStr)] string val, int n, IntPtr free); [DllImport("e_sqlite3", EntryPoint = "sqlite3_bind_blob", CallingConvention = CallingConvention.Cdecl)] - public static extern int BindBlob(IntPtr stmt, int index, byte[] val, int n, IntPtr free); + internal static extern int BindBlob(IntPtr stmt, int index, byte[] val, int n, IntPtr free); [DllImport("e_sqlite3", EntryPoint = "sqlite3_column_count", CallingConvention = CallingConvention.Cdecl)] - public static extern int ColumnCount(IntPtr stmt); + internal static extern int ColumnCount(IntPtr stmt); [DllImport("e_sqlite3", EntryPoint = "sqlite3_column_name", CallingConvention = CallingConvention.Cdecl)] - public static extern IntPtr ColumnName(IntPtr stmt, int index); + internal static extern IntPtr ColumnName(IntPtr stmt, int index); [DllImport("e_sqlite3", EntryPoint = "sqlite3_column_name16", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr ColumnName16Internal(IntPtr stmt, int index); @@ -2543,28 +2547,28 @@ public static string ColumnName16(IntPtr stmt, int index) { } [DllImport("e_sqlite3", EntryPoint = "sqlite3_column_type", CallingConvention = CallingConvention.Cdecl)] - public static extern ColType ColumnType(IntPtr stmt, int index); + internal static extern ColType ColumnType(IntPtr stmt, int index); [DllImport("e_sqlite3", EntryPoint = "sqlite3_column_int", CallingConvention = CallingConvention.Cdecl)] - public static extern int ColumnInt(IntPtr stmt, int index); + internal static extern int ColumnInt(IntPtr stmt, int index); [DllImport("e_sqlite3", EntryPoint = "sqlite3_column_int64", CallingConvention = CallingConvention.Cdecl)] - public static extern long ColumnInt64(IntPtr stmt, int index); + internal static extern long ColumnInt64(IntPtr stmt, int index); [DllImport("e_sqlite3", EntryPoint = "sqlite3_column_double", CallingConvention = CallingConvention.Cdecl)] - public static extern double ColumnDouble(IntPtr stmt, int index); + internal static extern double ColumnDouble(IntPtr stmt, int index); [DllImport("e_sqlite3", EntryPoint = "sqlite3_column_text", CallingConvention = CallingConvention.Cdecl)] - public static extern IntPtr ColumnText(IntPtr stmt, int index); + internal static extern IntPtr ColumnText(IntPtr stmt, int index); [DllImport("e_sqlite3", EntryPoint = "sqlite3_column_text16", CallingConvention = CallingConvention.Cdecl)] - public static extern IntPtr ColumnText16(IntPtr stmt, int index); + internal static extern IntPtr ColumnText16(IntPtr stmt, int index); [DllImport("e_sqlite3", EntryPoint = "sqlite3_column_blob", CallingConvention = CallingConvention.Cdecl)] - public static extern IntPtr ColumnBlob(IntPtr stmt, int index); + internal static extern IntPtr ColumnBlob(IntPtr stmt, int index); [DllImport("e_sqlite3", EntryPoint = "sqlite3_column_bytes", CallingConvention = CallingConvention.Cdecl)] - public static extern int ColumnBytes(IntPtr stmt, int index); + internal static extern int ColumnBytes(IntPtr stmt, int index); public static string ColumnString(IntPtr stmt, int index) { return Marshal.PtrToStringUni(SQLite3.ColumnText16(stmt, index)); diff --git a/WaveBox.Core/src/Static/ThreadSafeRandom.cs b/WaveBox.Core/src/Static/ThreadSafeRandom.cs index 8764e42..e3aa8ff 100644 --- a/WaveBox.Core/src/Static/ThreadSafeRandom.cs +++ b/WaveBox.Core/src/Static/ThreadSafeRandom.cs @@ -1,5 +1,4 @@ using System; -using System.Threading; namespace WaveBox.Core.Static { public static class ThreadSafeRandom { @@ -7,7 +6,7 @@ public static class ThreadSafeRandom { private static Random Local; public static Random ThisThreadsRandom { - get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId))); } + get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Environment.CurrentManagedThreadId))); } } } } diff --git a/WaveBox.Server/src/Api/ApiDispatcher.cs b/WaveBox.Server/src/Api/ApiDispatcher.cs index 1c3f8fc..4be4dc9 100644 --- a/WaveBox.Server/src/Api/ApiDispatcher.cs +++ b/WaveBox.Server/src/Api/ApiDispatcher.cs @@ -18,6 +18,8 @@ namespace WaveBox.Api { public class ApiDispatcher { private static readonly WaveBox.Core.Logging.ILog logger = WaveBox.Core.Logging.LogManager.GetLogger(typeof(ApiDispatcher)); + private static readonly char[] cookieSplitChars = new char[] { ';', ',', '=' }; + public async Task ProcessAsync(HttpContext context) { string method = context.Request.Method.ToUpperInvariant(); @@ -41,10 +43,10 @@ public async Task ProcessAsync(HttpContext context) { // Handlers are synchronous and may block (e.g. tailing a running transcode), so run the // legacy dispatch on a worker thread rather than tying up the request loop synchronously. - await Task.Run(() => this.Dispatch(context, rawUrl, method), context.RequestAborted); + await Task.Run(() => Dispatch(context, rawUrl, method), context.RequestAborted); } - private void Dispatch(HttpContext context, string rawUrl, string method) { + private static void Dispatch(HttpContext context, string rawUrl, string method) { UriWrapper uri = new UriWrapper(rawUrl, method); HttpContextProcessor processor = new HttpContextProcessor(context); @@ -63,7 +65,7 @@ private void Dispatch(HttpContext context, string rawUrl, string method) { // Check for valid API action ("web" and "error" are technically valid, but can't be used in this way) if (uri.ApiAction == null || uri.ApiAction == "web" || uri.ApiAction == "error") { - this.WriteError(uri, processor, apiUser, "Invalid API call"); + WriteError(uri, processor, apiUser, "Invalid API call"); logger.IfInfo(String.Format("[{0}] API: {1}", ip, rawUrl)); return; } @@ -71,7 +73,7 @@ private void Dispatch(HttpContext context, string rawUrl, string method) { // Check for session cookie authentication, unless this is a login request string sessionId = null; if (uri.ApiAction != "login") { - sessionId = this.GetSessionCookie(processor); + sessionId = GetSessionCookie(processor); apiUser = Injection.Get().AuthenticateSession(sessionId); } @@ -81,7 +83,7 @@ private void Dispatch(HttpContext context, string rawUrl, string method) { // If user still null, failed authentication, so serve error if (apiUser == null) { - this.WriteError(uri, processor, apiUser, "Authentication failed"); + WriteError(uri, processor, apiUser, "Authentication failed"); logger.IfInfo(String.Format("[{0}] API: {1}", ip, rawUrl)); return; } @@ -89,7 +91,7 @@ private void Dispatch(HttpContext context, string rawUrl, string method) { // apiUser.SessionId will be generated on new login, so that takes precedence for new session cookie apiUser.SessionId = apiUser.SessionId ?? sessionId; - this.SetSessionCookie(processor, apiUser.SessionId); + SetSessionCookie(processor, apiUser.SessionId); // Store user's current session object apiUser.CurrentSession = Injection.Get().SessionForSessionId(apiUser.SessionId); @@ -99,7 +101,7 @@ private void Dispatch(HttpContext context, string rawUrl, string method) { // Check for valid API action if (apiHandler == null) { - this.WriteError(uri, processor, apiUser, "Invalid API call"); + WriteError(uri, processor, apiUser, "Invalid API call"); logger.IfInfo(String.Format("[{0}] API: {1}", ip, rawUrl)); return; } @@ -109,7 +111,7 @@ private void Dispatch(HttpContext context, string rawUrl, string method) { // Check if user has appropriate permissions for this action on this API handler if (!apiHandler.CheckPermission(apiUser, uri.Action)) { - this.WriteError(uri, processor, apiUser, "Permission denied"); + WriteError(uri, processor, apiUser, "Permission denied"); return; } @@ -117,16 +119,15 @@ private void Dispatch(HttpContext context, string rawUrl, string method) { apiHandler.Process(uri, processor, apiUser); } - private void WriteError(UriWrapper uri, HttpContextProcessor processor, User user, string message) { - ErrorApiHandler errorApi = (ErrorApiHandler)Injection.Get().CreateApiHandler("error"); - errorApi.Process(uri, processor, user, message); + private static void WriteError(UriWrapper uri, HttpContextProcessor processor, User user, string message) { + ErrorApiHandler.Process(uri, processor, user, message); } // If a cookie is found, grab it and use it for authentication (legacy naive parsing, bug-compatible) - private string GetSessionCookie(HttpContextProcessor processor) { + private static string GetSessionCookie(HttpContextProcessor processor) { if (processor.HttpHeaders.ContainsKey("Cookie")) { // Split each cookie into pairs - string[] cookies = processor.HttpHeaders["Cookie"].ToString().Split(new[] { ';', ',', '=' }, StringSplitOptions.RemoveEmptyEntries); + string[] cookies = processor.HttpHeaders["Cookie"].ToString().Split(cookieSplitChars, StringSplitOptions.RemoveEmptyEntries); // Iterate all cookies for (int i = 0; i < cookies.Length - 1; i += 2) { @@ -141,7 +142,7 @@ private string GetSessionCookie(HttpContextProcessor processor) { } // Set a new session cookie to be set when the HTTP response is sent - private void SetSessionCookie(HttpContextProcessor processor, string sessionId) { + private static void SetSessionCookie(HttpContextProcessor processor, string sessionId) { if (sessionId != null) { // Calculate session timeout time (DateTime.UtcNow UTC + SessionTimeout minutes) DateTime expire = DateTime.UtcNow.ToUniversalTime().AddMinutes(Injection.Get().SessionTimeout); diff --git a/WaveBox.Server/src/Api/HttpContextProcessor.cs b/WaveBox.Server/src/Api/HttpContextProcessor.cs index dd008e2..1c959b7 100644 --- a/WaveBox.Server/src/Api/HttpContextProcessor.cs +++ b/WaveBox.Server/src/Api/HttpContextProcessor.cs @@ -163,11 +163,11 @@ public void WriteFile(Stream fs, int startOffset, long length, string mimeType, } long contentLength = length - actualStartOffset; - if (!ReferenceEquals(limitToBytes, null) && contentLength > limitToBytes) { + if (limitToBytes != null && contentLength > limitToBytes) { contentLength = (long)limitToBytes; } - bool isPartial = startOffset != 0 || !ReferenceEquals(limitToBytes, null); + bool isPartial = startOffset != 0 || limitToBytes != null; if (isPartial) { if (ReferenceEquals(customHeaders, null)) { customHeaders = new Dictionary(); @@ -188,7 +188,7 @@ public void WriteFile(Stream fs, int startOffset, long length, string mimeType, } int thisChunkSize = chunkSize; - if (!ReferenceEquals(limitToBytes, null)) { + if (limitToBytes != null) { // Make sure we don't send too much data on the last (potentially) partial chunk if (bytesWritten + chunkSize > limitToBytes) { thisChunkSize = (int)(limitToBytes - bytesWritten); @@ -205,7 +205,7 @@ public void WriteFile(Stream fs, int startOffset, long length, string mimeType, totalBytesWritten += bytesRead; // See if we need to stop the transfer to limit the size - if (!ReferenceEquals(limitToBytes, null) && bytesWritten == limitToBytes) { + if (limitToBytes != null && bytesWritten == limitToBytes) { break; } @@ -234,9 +234,9 @@ public void WriteFile(Stream fs, int startOffset, long length, string mimeType, } } - private DateTime CleanLastModified(DateTime? lastModified) { + private static DateTime CleanLastModified(DateTime? lastModified) { // If null, use current time - if (ReferenceEquals(lastModified, null)) { + if (lastModified == null) { return DateTime.UtcNow; } diff --git a/WaveBox.Server/src/ApiHandler/ApiAuthenticate.cs b/WaveBox.Server/src/ApiHandler/ApiAuthenticate.cs index 4165dec..4705c38 100644 --- a/WaveBox.Server/src/ApiHandler/ApiAuthenticate.cs +++ b/WaveBox.Server/src/ApiHandler/ApiAuthenticate.cs @@ -20,7 +20,7 @@ public User AuthenticateSession(string session) { User user = Injection.Get().UserForId((int)userId); if (user != null) { // Update this user's session and return - user.UpdateSession(session); + User.UpdateSession(session); return user; } } diff --git a/WaveBox.Server/src/ApiHandler/ArtStream.cs b/WaveBox.Server/src/ApiHandler/ArtStream.cs index d5349c0..55f493e 100644 --- a/WaveBox.Server/src/ApiHandler/ArtStream.cs +++ b/WaveBox.Server/src/ApiHandler/ArtStream.cs @@ -125,7 +125,7 @@ public static bool FolderContainsImages(string dir, out string firstImageFoundPa foreach (string file in Directory.GetFiles(dir)) { ext = Path.GetExtension(file).ToLower(); - if (validImageExtensions.Contains(ext) && !Path.GetFileName(file).StartsWith(".")) { + if (validImageExtensions.Contains(ext) && !Path.GetFileName(file).StartsWith('.')) { firstImageFoundPath = file; } } diff --git a/WaveBox.Server/src/ApiHandler/Handlers/AlbumArtistsApiHandler.cs b/WaveBox.Server/src/ApiHandler/Handlers/AlbumArtistsApiHandler.cs index 6f17160..a53c3fd 100644 --- a/WaveBox.Server/src/ApiHandler/Handlers/AlbumArtistsApiHandler.cs +++ b/WaveBox.Server/src/ApiHandler/Handlers/AlbumArtistsApiHandler.cs @@ -47,7 +47,7 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { counts.Add("albums", albums.Count); // If requested, add artist's songs to response - if (uri.Parameters.ContainsKey("includeSongs") && uri.Parameters["includeSongs"].IsTrue()) { + if (uri.Parameters.TryGetValue("includeSongs", out string includeSongsParam) && includeSongsParam.IsTrue()) { songs = a.ListOfSongs(); counts.Add("songs", songs.Count); } else { @@ -55,7 +55,7 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { } // If requested, add artist's Last.fm info to response - if (uri.Parameters.ContainsKey("lastfmInfo") && uri.Parameters["lastfmInfo"].IsTrue()) { + if (uri.Parameters.TryGetValue("lastfmInfo", out string lastfmInfoParam) && lastfmInfoParam.IsTrue()) { logger.IfInfo("Querying Last.fm for artist: " + a.AlbumArtistName); try { lastfmInfo = Lastfm.GetAlbumArtistInfo(a); @@ -75,8 +75,8 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { } } // Check for a request for range of artists - else if (uri.Parameters.ContainsKey("range")) { - string[] range = uri.Parameters["range"].Split(','); + else if (uri.Parameters.TryGetValue("range", out string rangeParam)) { + string[] range = rangeParam.Split(','); // Ensure valid range was parsed if (range.Length != 2) { @@ -97,8 +97,8 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { // Check for a request to limit/paginate artists, like SQL // Note: can be combined with range or all artists - if (uri.Parameters.ContainsKey("limit") && uri.Id == null) { - string[] limit = uri.Parameters["limit"].Split(','); + if (uri.Parameters.TryGetValue("limit", out string limitParam) && uri.Id == null) { + string[] limit = limitParam.Split(','); // Ensure valid limit was parsed if (limit.Length < 1 || limit.Length > 2 ) { diff --git a/WaveBox.Server/src/ApiHandler/Handlers/AlbumsApiHandler.cs b/WaveBox.Server/src/ApiHandler/Handlers/AlbumsApiHandler.cs index 97668b3..1b0ce2e 100644 --- a/WaveBox.Server/src/ApiHandler/Handlers/AlbumsApiHandler.cs +++ b/WaveBox.Server/src/ApiHandler/Handlers/AlbumsApiHandler.cs @@ -42,8 +42,8 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { songs = a.ListOfSongs(); } // Check for a request for range of songs - else if (uri.Parameters.ContainsKey("range")) { - string[] range = uri.Parameters["range"].Split(','); + else if (uri.Parameters.TryGetValue("range", out string rangeParam)) { + string[] range = rangeParam.Split(','); // Ensure valid range was parsed if (range.Length != 2) { @@ -64,8 +64,8 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { // Check for a request to limit/paginate songs, like SQL // Note: can be combined with range or all albums - if (uri.Parameters.ContainsKey("limit") && uri.Id == null) { - string[] limit = uri.Parameters["limit"].Split(','); + if (uri.Parameters.TryGetValue("limit", out string limitParam) && uri.Id == null) { + string[] limit = limitParam.Split(','); // Ensure valid limit was parsed if (limit.Length < 1 || limit.Length > 2 ) { diff --git a/WaveBox.Server/src/ApiHandler/Handlers/ArtApiHandler.cs b/WaveBox.Server/src/ApiHandler/Handlers/ArtApiHandler.cs index 7b14b59..7a41fd9 100644 --- a/WaveBox.Server/src/ApiHandler/Handlers/ArtApiHandler.cs +++ b/WaveBox.Server/src/ApiHandler/Handlers/ArtApiHandler.cs @@ -38,9 +38,7 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { // Check for blur (value between 0 and 100) double blurSigma = 0; - if (uri.Parameters.ContainsKey("blur")) { - int blur = 0; - Int32.TryParse(uri.Parameters["blur"], out blur); + if (uri.Parameters.TryGetValue("blur", out string blurParam) && Int32.TryParse(blurParam, out int blur)) { if (blur < 0) { blur = 0; } else if (blur > 100) { @@ -60,26 +58,20 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { return; } - // If art size requested... - if (uri.Parameters.ContainsKey("size")) { - int size = Int32.MaxValue; - Int32.TryParse(uri.Parameters["size"], out size); - - // Parse size if valid - if (size != Int32.MaxValue) { - try { - Stream resized = ArtStream.ResizeImage(stream, size, blurSigma); - stream.Close(); - stream = resized; - } catch (Exception e) { - logger.Error("Error resizing art, returning original: ", e); - stream.Position = 0; - } + // If a valid art size requested, resize + if (uri.Parameters.TryGetValue("size", out string sizeParam) && Int32.TryParse(sizeParam, out int size)) { + try { + Stream resized = ArtStream.ResizeImage(stream, size, blurSigma); + stream.Close(); + stream = resized; + } catch (Exception e) { + logger.Error("Error resizing art, returning original: ", e); + stream.Position = 0; } } DateTime? lastModified = null; - if (!ReferenceEquals(art.LastModified, null)) { + if (art.LastModified != null) { lastModified = ((long)art.LastModified).ToDateTime(); } processor.WriteFile(stream, 0, stream.Length, HttpHeader.MimeTypeForExtension(".jpg"), null, true, lastModified); diff --git a/WaveBox.Server/src/ApiHandler/Handlers/ArtistsApiHandler.cs b/WaveBox.Server/src/ApiHandler/Handlers/ArtistsApiHandler.cs index 3d78d28..6fe37dc 100644 --- a/WaveBox.Server/src/ApiHandler/Handlers/ArtistsApiHandler.cs +++ b/WaveBox.Server/src/ApiHandler/Handlers/ArtistsApiHandler.cs @@ -52,7 +52,7 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { counts.Add("albums", albums.Count); // If requested, add artist's songs to response - if (uri.Parameters.ContainsKey("includeSongs") && uri.Parameters["includeSongs"].IsTrue()) { + if (uri.Parameters.TryGetValue("includeSongs", out string includeSongsParam) && includeSongsParam.IsTrue()) { songs = a.ListOfSongs(); counts.Add("songs", songs.Count); } else { @@ -60,7 +60,7 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { } // If requested, add artist's Last.fm info to response - if (uri.Parameters.ContainsKey("lastfmInfo") && uri.Parameters["lastfmInfo"].IsTrue()) { + if (uri.Parameters.TryGetValue("lastfmInfo", out string lastfmInfoParam) && lastfmInfoParam.IsTrue()) { logger.IfInfo("Querying Last.fm for artist: " + a.ArtistName); try { lastfmInfo = Lastfm.GetArtistInfo(a); @@ -76,8 +76,8 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { counts.Add("favorites", numFavorites); } // Check for a request for range of artists - else if (uri.Parameters.ContainsKey("range")) { - string[] range = uri.Parameters["range"].Split(','); + else if (uri.Parameters.TryGetValue("range", out string rangeParam)) { + string[] range = rangeParam.Split(','); // Ensure valid range was parsed if (range.Length != 2) { @@ -98,8 +98,8 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { // Check for a request to limit/paginate artists, like SQL // Note: can be combined with range or all artists - if (uri.Parameters.ContainsKey("limit") && !uri.Parameters.ContainsKey("id")) { - string[] limit = uri.Parameters["limit"].Split(','); + if (uri.Parameters.TryGetValue("limit", out string limitParam) && !uri.Parameters.ContainsKey("id")) { + string[] limit = limitParam.Split(','); // Ensure valid limit was parsed if (limit.Length < 1 || limit.Length > 2 ) { diff --git a/WaveBox.Server/src/ApiHandler/Handlers/DatabaseApiHandler.cs b/WaveBox.Server/src/ApiHandler/Handlers/DatabaseApiHandler.cs index 558e5fa..2e30636 100644 --- a/WaveBox.Server/src/ApiHandler/Handlers/DatabaseApiHandler.cs +++ b/WaveBox.Server/src/ApiHandler/Handlers/DatabaseApiHandler.cs @@ -46,20 +46,20 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { try { // Read in entire database file - Stream stream = new FileStream(ServerUtility.RootPath() + databaseFileName, FileMode.Open, FileAccess.Read); + FileStream stream = new FileStream(ServerUtility.RootPath() + databaseFileName, FileMode.Open, FileAccess.Read); long length = stream.Length; int startOffset = 0; // Handle the Range header to start from later in the file if connection interrupted if (processor.HttpHeaders.ContainsKey("Range")) { string range = (string)processor.HttpHeaders["Range"]; - string start = range.Split(new char[] {'-', '='})[1]; + string start = range.Split('-', '=')[1]; logger.IfInfo("Connection retried. Resuming from " + start); startOffset = Convert.ToInt32(start); } // We send the last query id as a custom header - IDictionary customHeader = new Dictionary(); + Dictionary customHeader = new Dictionary(); customHeader["WaveBox-LastQueryId"] = databaseLastQueryId.ToString(); // Send the database file diff --git a/WaveBox.Server/src/ApiHandler/Handlers/ErrorApiHandler.cs b/WaveBox.Server/src/ApiHandler/Handlers/ErrorApiHandler.cs index d3df5cb..6e1777e 100644 --- a/WaveBox.Server/src/ApiHandler/Handlers/ErrorApiHandler.cs +++ b/WaveBox.Server/src/ApiHandler/Handlers/ErrorApiHandler.cs @@ -24,13 +24,13 @@ public bool CheckPermission(User user, string action) { /// Overload for IApiHandler interface /// public void Process(UriWrapper uri, IHttpProcessor processor, User user) { - this.Process(uri, processor, user, "Invalid API call"); + Process(uri, processor, user, "Invalid API call"); } /// /// Process logs the error, creates a JSON response, and send it back to the user on bad API call /// - public void Process(UriWrapper uri, IHttpProcessor processor, User user, string error) { + public static void Process(UriWrapper uri, IHttpProcessor processor, User user, string error) { logger.Error(error); ErrorResponse response = new ErrorResponse(error); diff --git a/WaveBox.Server/src/ApiHandler/Handlers/FoldersApiHandler.cs b/WaveBox.Server/src/ApiHandler/Handlers/FoldersApiHandler.cs index c284faa..6035842 100644 --- a/WaveBox.Server/src/ApiHandler/Handlers/FoldersApiHandler.cs +++ b/WaveBox.Server/src/ApiHandler/Handlers/FoldersApiHandler.cs @@ -40,7 +40,7 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { containingFolder = Injection.Get().FolderForId((int)uri.Id); listOfFolders = containingFolder.ListOfSubFolders(); - if (uri.Parameters.ContainsKey("recursiveMedia") && uri.Parameters["recursiveMedia"].IsTrue()) { + if (uri.Parameters.TryGetValue("recursiveMedia", out string recursiveMediaParam) && recursiveMediaParam.IsTrue()) { recursive = true; } @@ -54,7 +54,7 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { } // No id parameter - if (uri.Parameters.ContainsKey("mediaFolders") && uri.Parameters["mediaFolders"].IsTrue()) { + if (uri.Parameters.TryGetValue("mediaFolders", out string mediaFoldersParam) && mediaFoldersParam.IsTrue()) { // They asked for the media folders listOfFolders = Injection.Get().MediaFolders(); } else { diff --git a/WaveBox.Server/src/ApiHandler/Handlers/GenresApiHandler.cs b/WaveBox.Server/src/ApiHandler/Handlers/GenresApiHandler.cs index 72a353c..5b5b9fe 100644 --- a/WaveBox.Server/src/ApiHandler/Handlers/GenresApiHandler.cs +++ b/WaveBox.Server/src/ApiHandler/Handlers/GenresApiHandler.cs @@ -36,8 +36,8 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { if (uri.Id != null) { // Default: artists string type = "artists"; - if (uri.Parameters.ContainsKey("type")) { - type = uri.Parameters["type"]; + if (uri.Parameters.TryGetValue("type", out string typeParam)) { + type = typeParam; } // Get single genre, add it for output diff --git a/WaveBox.Server/src/ApiHandler/Handlers/NowPlayingApiHandler.cs b/WaveBox.Server/src/ApiHandler/Handlers/NowPlayingApiHandler.cs index 1eb4d29..0e17616 100644 --- a/WaveBox.Server/src/ApiHandler/Handlers/NowPlayingApiHandler.cs +++ b/WaveBox.Server/src/ApiHandler/Handlers/NowPlayingApiHandler.cs @@ -37,13 +37,13 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { IList nowPlaying = nowPlayingService.Playing; // Filter by user name - if (uri.Parameters.ContainsKey("user")) { - nowPlaying = nowPlaying.Where(x => x.User.UserName == uri.Parameters["user"]).ToList(); + if (uri.Parameters.TryGetValue("user", out string userName)) { + nowPlaying = nowPlaying.Where(x => x.User.UserName == userName).ToList(); } // Filter by client name - if (uri.Parameters.ContainsKey("client")) { - nowPlaying = nowPlaying.Where(x => x.User.CurrentSession.ClientName == uri.Parameters["client"]).ToList(); + if (uri.Parameters.TryGetValue("client", out string clientName)) { + nowPlaying = nowPlaying.Where(x => x.User.CurrentSession.ClientName == clientName).ToList(); } // Return list of now playing items diff --git a/WaveBox.Server/src/ApiHandler/Handlers/PlaylistsApiHandler.cs b/WaveBox.Server/src/ApiHandler/Handlers/PlaylistsApiHandler.cs index 52bf1e4..6e42207 100644 --- a/WaveBox.Server/src/ApiHandler/Handlers/PlaylistsApiHandler.cs +++ b/WaveBox.Server/src/ApiHandler/Handlers/PlaylistsApiHandler.cs @@ -51,8 +51,8 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { if (uri.Action == "create") { // Try to get the name string name = null; - if (uri.Parameters.ContainsKey("name")) { - name = HttpUtility.UrlDecode(uri.Parameters["name"]); + if (uri.Parameters.TryGetValue("name", out string nameParam)) { + name = HttpUtility.UrlDecode(nameParam); } // Verify non-null name @@ -73,7 +73,7 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { playlist.CreatePlaylist(); // Try to get the itemIds to add them to the playlist if necessary - IList itemIds = this.ParseItemIds(uri); + List itemIds = ParseItemIds(uri); if (itemIds.Count > 0) { playlist.AddMediaItems(itemIds); } @@ -113,7 +113,7 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { // add - add items to a playlist if (uri.Action == "add") { // Try to get the itemIds to add them to the playlist if necessary - IList itemIds = this.ParseItemIds(uri); + List itemIds = ParseItemIds(uri); if (itemIds.Count == 0) { processor.WriteJson(new PlaylistsResponse("No item IDs found in URL", null, null, null)); return; @@ -174,8 +174,8 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { // insert - insert item in playlist at specified index if (uri.Action == "insert") { - IList insertItemIds = this.ParseItemIds(uri); - IList insertIndexes = this.ParseIndexes(uri); + List insertItemIds = ParseItemIds(uri); + List insertIndexes = ParseIndexes(uri); if (insertItemIds.Count == 0 || insertItemIds.Count != insertIndexes.Count) { processor.WriteJson(new PlaylistsResponse("Incorrect number of items and indices supplied for action 'insert'", null, null, null)); return; @@ -198,7 +198,7 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { // move - move an item in the playlist if (uri.Action == "move") { - IList moveIndexes = this.ParseIndexes(uri); + List moveIndexes = ParseIndexes(uri); if (moveIndexes.Count == 0 || moveIndexes.Count % 2 != 0) { processor.WriteJson(new PlaylistsResponse("Incorrect number of indices supplied for action 'move'", null, null, null)); return; @@ -220,7 +220,7 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { // remove - remove items from playlist if (uri.Action == "remove") { - IList removeIndexes = this.ParseIndexes(uri); + List removeIndexes = ParseIndexes(uri); if (removeIndexes.Count == 0) { processor.WriteJson(new PlaylistsResponse("No indices supplied for action 'remove'", null, null, null)); return; @@ -240,11 +240,11 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { return; } - private IList ParseItemIds(UriWrapper uri) { + private static List ParseItemIds(UriWrapper uri) { // Try to get the itemIds - IList itemIds = new List(); - if (uri.Parameters.ContainsKey("itemIds")) { - string[] itemIdStrings = uri.Parameters["itemIds"].Split(','); + List itemIds = new List(); + if (uri.Parameters.TryGetValue("itemIds", out string itemIdsParam)) { + string[] itemIdStrings = itemIdsParam.Split(','); foreach (string itemIdString in itemIdStrings) { int itemId; @@ -257,11 +257,11 @@ private IList ParseItemIds(UriWrapper uri) { return itemIds; } - private IList ParseIndexes(UriWrapper uri) { + private static List ParseIndexes(UriWrapper uri) { // Try to get the itemIds - IList itemIds = new List(); - if (uri.Parameters.ContainsKey("indexes")) { - string[] itemIdStrings = uri.Parameters["indexes"].Split(','); + List itemIds = new List(); + if (uri.Parameters.TryGetValue("indexes", out string indexesParam)) { + string[] itemIdStrings = indexesParam.Split(','); foreach (string itemIdString in itemIdStrings) { int itemId; diff --git a/WaveBox.Server/src/ApiHandler/Handlers/ScrobbleApiHandler.cs b/WaveBox.Server/src/ApiHandler/Handlers/ScrobbleApiHandler.cs index 6fec581..56d17ca 100644 --- a/WaveBox.Server/src/ApiHandler/Handlers/ScrobbleApiHandler.cs +++ b/WaveBox.Server/src/ApiHandler/Handlers/ScrobbleApiHandler.cs @@ -52,7 +52,7 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { } // Create list of scrobble data - IList scrobbles = new List(); + List scrobbles = new List(); // Get Last.fm API enumerations LfmScrobbleType scrobbleType = Lastfm.ScrobbleTypeForString(uri.Action); diff --git a/WaveBox.Server/src/ApiHandler/Handlers/SearchApiHandler.cs b/WaveBox.Server/src/ApiHandler/Handlers/SearchApiHandler.cs index 0b38167..dc8a576 100644 --- a/WaveBox.Server/src/ApiHandler/Handlers/SearchApiHandler.cs +++ b/WaveBox.Server/src/ApiHandler/Handlers/SearchApiHandler.cs @@ -32,13 +32,13 @@ public void Process(UriWrapper uri, IHttpProcessor processor, User user) { IList