From 9bfedf3cf0e7d0e8f37f525a106dcf475cd7276a Mon Sep 17 00:00:00 2001 From: Flamefire Date: Wed, 25 Sep 2013 20:19:22 +0200 Subject: [PATCH 01/18] Rename SScores --- Vocaluxe/Base/CDataBase.cs | 8 ++++---- Vocaluxe/Screens/CScreenHighscore.cs | 8 ++++---- VocaluxeLib/Structs.cs | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Vocaluxe/Base/CDataBase.cs b/Vocaluxe/Base/CDataBase.cs index b755a95b..cf37bf3b 100644 --- a/Vocaluxe/Base/CDataBase.cs +++ b/Vocaluxe/Base/CDataBase.cs @@ -243,13 +243,13 @@ namespace Vocaluxe.Base return lastInsertID; } - public static void LoadScore(out List scores, SPlayer player) + public static void LoadScore(out List scores, SPlayer player) { using (var connection = new SQLiteConnection()) { connection.ConnectionString = "Data Source=" + _HighscoreFilePath; - scores = new List(); + scores = new List(); try { @@ -290,13 +290,13 @@ namespace Vocaluxe.Base { while (reader.Read()) { - var score = new SScores + var score = new SDBScoreEntry { Name = reader.GetString(0), Score = reader.GetInt32(1), Date = new DateTime(reader.GetInt64(2)).ToString("dd/MM/yyyy"), Difficulty = (EGameDifficulty)reader.GetInt32(3), - LineNr = reader.GetInt32(4), + VoiceNr = reader.GetInt32(4), ID = reader.GetInt32(5) }; diff --git a/Vocaluxe/Screens/CScreenHighscore.cs b/Vocaluxe/Screens/CScreenHighscore.cs index 933c2706..a8be7e46 100644 --- a/Vocaluxe/Screens/CScreenHighscore.cs +++ b/Vocaluxe/Screens/CScreenHighscore.cs @@ -44,7 +44,7 @@ namespace Vocaluxe.Screens private string[] _TextDate; private string[] _ParticleEffectNew; - private List[] _Scores; + private List[] _Scores; private List _NewEntryIDs; private int _Round; private int _Pos; @@ -169,7 +169,7 @@ namespace Vocaluxe.Screens string name = _Scores[_Round][_Pos + p].Name; name += " [" + CLanguage.Translate(Enum.GetName(typeof(EGameDifficulty), _Scores[_Round][_Pos + p].Difficulty)) + "]"; if (_IsDuet) - name += " (P" + (_Scores[_Round][_Pos + p].LineNr + 1) + ")"; + name += " (P" + (_Scores[_Round][_Pos + p].VoiceNr + 1) + ")"; _Texts[_TextName[p]].Text = name; _Texts[_TextScore[p]].Text = _Scores[_Round][_Pos + p].Score.ToString("00000"); @@ -195,9 +195,9 @@ namespace Vocaluxe.Screens _Round = 0; _Pos = 0; CPoints points = CGame.GetPoints(); - _Scores = new List[points.NumRounds]; + _Scores = new List[points.NumRounds]; for (int i = 0; i < _Scores.Length; i++) - _Scores[i] = new List(); + _Scores[i] = new List(); _NewEntryIDs.Clear(); _AddScoresToDB(); _LoadScores(); diff --git a/VocaluxeLib/Structs.cs b/VocaluxeLib/Structs.cs index 4bef014d..895d593b 100644 --- a/VocaluxeLib/Structs.cs +++ b/VocaluxeLib/Structs.cs @@ -197,13 +197,13 @@ namespace VocaluxeLib public bool SongFinished; } - public struct SScores + public struct SDBScoreEntry { public string Name; public int Score; public string Date; public EGameDifficulty Difficulty; - public int LineNr; + public int VoiceNr; public int ID; } From e3f744677e25a29cf7e6a89d6bf1eb989f23e398 Mon Sep 17 00:00:00 2001 From: Flamefire Date: Thu, 26 Sep 2013 13:47:19 +0200 Subject: [PATCH 02/18] Better handling of Points (Preparation for future changes) Fix some warnings of unused results (show errors on failure!) --- Vocaluxe/Base/CDataBase.cs | 206 +++++++++++++-------------- Vocaluxe/Base/CGame.cs | 6 +- Vocaluxe/Screens/CScreenCredits.cs | 30 ++-- Vocaluxe/Screens/CScreenHighscore.cs | 2 +- Vocaluxe/SongQueue/CSongQueue.cs | 4 +- VocaluxeLib/Game/CPoints.cs | 14 +- VocaluxeLib/Structs.cs | 4 +- 7 files changed, 129 insertions(+), 137 deletions(-) diff --git a/Vocaluxe/Base/CDataBase.cs b/Vocaluxe/Base/CDataBase.cs index cf37bf3b..ada2a0a6 100644 --- a/Vocaluxe/Base/CDataBase.cs +++ b/Vocaluxe/Base/CDataBase.cs @@ -63,8 +63,16 @@ namespace Vocaluxe.Base _CreditsRessourcesFilePath = Path.Combine(Environment.CurrentDirectory, CSettings.FileCreditsRessourcesDB); _InitHighscoreDB(); - _InitCoverDB(); - _InitCreditsRessourcesDB(); + if (!_InitCoverDB()) + { + CLog.LogError("Error initializing Cover-DB", true, true); + return; + } + if (!_InitCreditsRessourcesDB()) + { + CLog.LogError("Error initializing Cover-DB", true, true); + return; + } GC.Collect(); } @@ -93,26 +101,6 @@ namespace Vocaluxe.Base return _GetDataBaseSongInfos(songID, out sArtist, out sTitle, out numPlayed, out dateAdded, _HighscoreFilePath); } - public static void IncreaseSongCounter(SPlayer player) - { - using (var connection = new SQLiteConnection()) - { - connection.ConnectionString = "Data Source=" + _HighscoreFilePath; - - try - { - connection.Open(); - } - catch (Exception) {} - - using (var command = new SQLiteCommand(connection)) - { - int dataBaseSongID = _GetDataBaseSongID(player, command); - _IncreaseSongCounter(dataBaseSongID, command); - } - } - } - public static void IncreaseSongCounter(int dataBaseSongID) { using (var connection = new SQLiteConnection()) @@ -170,11 +158,27 @@ namespace Vocaluxe.Base return -1; } + int medley = 0; + int duet = 0; + int shortSong = 0; + switch (player.GameMode) + { + case EGameMode.TR_GAMEMODE_MEDLEY: + medley = 1; + break; + case EGameMode.TR_GAMEMODE_DUET: + duet = 1; + break; + case EGameMode.TR_GAMEMODE_SHORTSONG: + shortSong = 1; + break; + } + using (var command = new SQLiteCommand(connection)) { int dataBaseSongID = CSongs.GetSong(player.SongID).DataBaseSongID; - return _AddScore(CProfiles.GetPlayerName(player.ProfileID), (int)Math.Round(player.Points), player.VoiceNr, player.DateTicks, player.Medley ? 1 : 0, - player.Duet ? 1 : 0, player.ShortSong ? 1 : 0, (int)CProfiles.GetDifficulty(player.ProfileID), dataBaseSongID, command); + return _AddScore(CProfiles.GetPlayerName(player.ProfileID), (int)Math.Round(player.Points), player.VoiceNr, player.DateTicks, medley, + duet, shortSong, (int)CProfiles.GetDifficulty(player.ProfileID), dataBaseSongID, command); } } } @@ -243,7 +247,7 @@ namespace Vocaluxe.Base return lastInsertID; } - public static void LoadScore(out List scores, SPlayer player) + public static void LoadScore(out List scores, int songID, EGameMode gameMode) { using (var connection = new SQLiteConnection()) { @@ -263,47 +267,51 @@ namespace Vocaluxe.Base using (var command = new SQLiteCommand(connection)) { int medley = 0; - if (player.Medley) - medley = 1; - int duet = 0; - if (player.Duet) - duet = 1; - int shortSong = 0; - if (player.ShortSong) - shortSong = 1; - - int dataBaseSongID = _GetDataBaseSongID(player, command); - if (dataBaseSongID >= 0) + switch (gameMode) { - command.CommandText = "SELECT PlayerName, Score, Date, Difficulty, LineNr, id FROM Scores " + - "WHERE [SongID] = @SongID AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " + - "ORDER BY [Score] DESC"; - command.Parameters.Add("@SongID", DbType.Int32, 0).Value = dataBaseSongID; - command.Parameters.Add("@Medley", DbType.Int32, 0).Value = medley; - command.Parameters.Add("@Duet", DbType.Int32, 0).Value = duet; - command.Parameters.Add("@ShortSong", DbType.Int32, 0).Value = shortSong; + case EGameMode.TR_GAMEMODE_MEDLEY: + medley = 1; + break; + case EGameMode.TR_GAMEMODE_DUET: + duet = 1; + break; + case EGameMode.TR_GAMEMODE_SHORTSONG: + shortSong = 1; + break; + } - SQLiteDataReader reader = command.ExecuteReader(); - if (reader != null && reader.HasRows) + int dataBaseSongID = _GetDataBaseSongID(songID, command); + if (dataBaseSongID < 0) + return; + + command.CommandText = "SELECT PlayerName, Score, Date, Difficulty, LineNr, id FROM Scores " + + "WHERE [SongID] = @SongID AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " + + "ORDER BY [Score] DESC"; + command.Parameters.Add("@SongID", DbType.Int32, 0).Value = dataBaseSongID; + command.Parameters.Add("@Medley", DbType.Int32, 0).Value = medley; + command.Parameters.Add("@Duet", DbType.Int32, 0).Value = duet; + command.Parameters.Add("@ShortSong", DbType.Int32, 0).Value = shortSong; + + SQLiteDataReader reader = command.ExecuteReader(); + if (reader != null && reader.HasRows) + { + while (reader.Read()) { - while (reader.Read()) - { - var score = new SDBScoreEntry - { - Name = reader.GetString(0), - Score = reader.GetInt32(1), - Date = new DateTime(reader.GetInt64(2)).ToString("dd/MM/yyyy"), - Difficulty = (EGameDifficulty)reader.GetInt32(3), - VoiceNr = reader.GetInt32(4), - ID = reader.GetInt32(5) - }; + var score = new SDBScoreEntry + { + Name = reader.GetString(0), + Score = reader.GetInt32(1), + Date = new DateTime(reader.GetInt64(2)).ToString("dd/MM/yyyy"), + Difficulty = (EGameDifficulty)reader.GetInt32(3), + VoiceNr = reader.GetInt32(4), + ID = reader.GetInt32(5) + }; - scores.Add(score); - } - reader.Dispose(); + scores.Add(score); } + reader.Dispose(); } } } @@ -316,9 +324,9 @@ namespace Vocaluxe.Base command.ExecuteNonQuery(); } - private static int _GetDataBaseSongID(SPlayer player, SQLiteCommand command) + private static int _GetDataBaseSongID(int songID, SQLiteCommand command) { - CSong song = CSongs.GetSong(player.SongID); + CSong song = CSongs.GetSong(songID); if (song == null) return -1; @@ -430,21 +438,35 @@ namespace Vocaluxe.Base { if (File.Exists(_HighscoreFilePath)) { - _CreateOrConvert(oldDBFilePath); - _CreateOrConvert(_HighscoreFilePath); - _ImportData(oldDBFilePath); - - File.Delete(oldDBFilePath); + if (!_CreateOrConvert(oldDBFilePath)) + { + CLog.LogError("Cannot init Highscore DB: Error opening database: " + oldDBFilePath, true, true); + return; + } + if (!_CreateOrConvert(_HighscoreFilePath)) + { + CLog.LogError("Cannot init Highscore DB: Error opening database: " + _HighscoreFilePath, true, true); + return; + } + if (!_ImportData(oldDBFilePath)) + { + CLog.LogError("Cannot init Highscore DB: Error importing data", true, true); + return; + } } else { File.Copy(oldDBFilePath, _HighscoreFilePath); - _CreateOrConvert(_HighscoreFilePath); - File.Delete(oldDBFilePath); + if (!_CreateOrConvert(_HighscoreFilePath)) + { + CLog.LogError("Cannot init Highscore DB: Error opening database: " + _HighscoreFilePath, true, true); + return; + } } + File.Delete(oldDBFilePath); } - else - _CreateOrConvert(_HighscoreFilePath); + else if (!_CreateOrConvert(_HighscoreFilePath)) + CLog.LogError("Cannot init Highscore DB: Error opening database: " + _HighscoreFilePath, true, true); } private static void _CreateHighscoreDB(string filePath) @@ -525,6 +547,7 @@ namespace Vocaluxe.Base /// private static bool _CreateOrConvert(string filePath) { + bool result = true; using (var connection = new SQLiteConnection()) { connection.ConnectionString = "Data Source=" + filePath; @@ -565,46 +588,24 @@ namespace Vocaluxe.Base } catch (Exception) {} - if (reader == null) + if (reader == null || reader.FieldCount == 0) { // create new database/tables if (version == 1) { //Check for USDX 1.1 DB _CreateHighscoreDBV1(filePath); - _ConvertFrom110(filePath); - _UpdateDatabase(1, connection); - _UpdateDatabase(2, connection); + result &= !_ConvertFrom110(filePath); + result &= _UpdateDatabase(1, connection); + result &= _UpdateDatabase(2, connection); } else if (version == 0 && scoresTableExists) { //Check for USDX 1.01 or CMD Mod DB _CreateHighscoreDBV1(filePath); - _ConvertFrom101(filePath); - _UpdateDatabase(1, connection); - _UpdateDatabase(2, connection); - } - else - _CreateHighscoreDB(filePath); - } - else if (reader.FieldCount == 0) - { - // create new database/tables - if (version == 1) - { - //Check for USDX 1.1 DB - _CreateHighscoreDBV1(filePath); - _ConvertFrom110(filePath); - _UpdateDatabase(1, connection); - _UpdateDatabase(2, connection); - } - else if (version == 0 && scoresTableExists) - { - //Check for USDX 1.01 or CMD Mod DB - _CreateHighscoreDBV1(filePath); - _ConvertFrom101(filePath); - _UpdateDatabase(1, connection); - _UpdateDatabase(2, connection); + result &= _ConvertFrom101(filePath); + result &= _UpdateDatabase(1, connection); + result &= _UpdateDatabase(2, connection); } else _CreateHighscoreDB(filePath); @@ -616,7 +617,7 @@ namespace Vocaluxe.Base if (currentVersion < CSettings.DatabaseHighscoreVersion) { // update database - _UpdateDatabase(currentVersion, connection); + result &= _UpdateDatabase(currentVersion, connection); } } @@ -625,7 +626,7 @@ namespace Vocaluxe.Base } } - return true; + return result; } /// @@ -972,8 +973,7 @@ namespace Vocaluxe.Base lastDateAdded = dateAdded; } } - if (reader != null) - reader.Dispose(); + reader.Dispose(); foreach (int id in ids) _IncreaseSongCounter(id, command); diff --git a/Vocaluxe/Base/CGame.cs b/Vocaluxe/Base/CGame.cs index dced2fa5..c64eaabc 100644 --- a/Vocaluxe/Base/CGame.cs +++ b/Vocaluxe/Base/CGame.cs @@ -197,9 +197,7 @@ namespace Vocaluxe.Base Players[i].CurrentLine = -1; Players[i].CurrentNote = -1; Players[i].SongID = -1; - Players[i].Medley = false; - Players[i].Duet = false; - Players[i].ShortSong = false; + Players[i].GameMode = EGameMode.TR_GAMEMODE_NORMAL; Players[i].DateTicks = DateTime.Now.Ticks; Players[i].SongFinished = false; } @@ -384,7 +382,7 @@ namespace Vocaluxe.Base { if (note.StartBeat < nextStart) { - if (note.Hit && note.HitNote.NoteType==ENoteType.Golden) + if (note.Hit && note.HitNote.NoteType == ENoteType.Golden) Players[p].PointsGoldenNotes += note.Points; Players[p].Points += note.Points; } diff --git a/Vocaluxe/Screens/CScreenCredits.cs b/Vocaluxe/Screens/CScreenCredits.cs index 06d36d1f..7c340a7a 100644 --- a/Vocaluxe/Screens/CScreenCredits.cs +++ b/Vocaluxe/Screens/CScreenCredits.cs @@ -183,24 +183,28 @@ namespace Vocaluxe.Screens public override void LoadTheme(string xmlPath) { + bool ressourceOK = true; //Vocaluxe-Logo - CDataBase.GetCreditsRessource("Logo_voc.png", ref _TexLogo); + ressourceOK &= CDataBase.GetCreditsRessource("Logo_voc.png", ref _TexLogo); //Little stars for logo - CDataBase.GetCreditsRessource("PerfectNoteStar.png", ref _TexPerfectNoteStar); + ressourceOK &= CDataBase.GetCreditsRessource("PerfectNoteStar.png", ref _TexPerfectNoteStar); - CDataBase.GetCreditsRessource("redDot.png", ref _TexRedDot); - CDataBase.GetCreditsRessource("blueDot.png", ref _TexBlueDot); + ressourceOK &= CDataBase.GetCreditsRessource("redDot.png", ref _TexRedDot); + ressourceOK &= CDataBase.GetCreditsRessource("blueDot.png", ref _TexBlueDot); - CDataBase.GetCreditsRessource("brunzel.png", ref _TexNameBrunzel); - CDataBase.GetCreditsRessource("Darkice.png", ref _TexNameDarkice); - CDataBase.GetCreditsRessource("flokuep.png", ref _TexNameFlokuep); - CDataBase.GetCreditsRessource("flamefire.png", ref _TexNameFlamefire); - CDataBase.GetCreditsRessource("bohning.png", ref _TexNameBohning); - CDataBase.GetCreditsRessource("mesand.png", ref _TexNameMesand); - CDataBase.GetCreditsRessource("babene03.png", ref _TexNameBabene03); - CDataBase.GetCreditsRessource("pantero.png", ref _TexNamePantero); - CDataBase.GetCreditsRessource("Pinky007.png", ref _TexNamePinky007); + ressourceOK &= CDataBase.GetCreditsRessource("brunzel.png", ref _TexNameBrunzel); + ressourceOK &= CDataBase.GetCreditsRessource("Darkice.png", ref _TexNameDarkice); + ressourceOK &= CDataBase.GetCreditsRessource("flokuep.png", ref _TexNameFlokuep); + ressourceOK &= CDataBase.GetCreditsRessource("flamefire.png", ref _TexNameFlamefire); + ressourceOK &= CDataBase.GetCreditsRessource("bohning.png", ref _TexNameBohning); + ressourceOK &= CDataBase.GetCreditsRessource("mesand.png", ref _TexNameMesand); + ressourceOK &= CDataBase.GetCreditsRessource("babene03.png", ref _TexNameBabene03); + ressourceOK &= CDataBase.GetCreditsRessource("pantero.png", ref _TexNamePantero); + ressourceOK &= CDataBase.GetCreditsRessource("Pinky007.png", ref _TexNamePinky007); + + if (!ressourceOK) + CLog.LogError("Could not load all ressources!", true, true); //Prepare Text int lastY = 280; diff --git a/Vocaluxe/Screens/CScreenHighscore.cs b/Vocaluxe/Screens/CScreenHighscore.cs index a8be7e46..9a75c943 100644 --- a/Vocaluxe/Screens/CScreenHighscore.cs +++ b/Vocaluxe/Screens/CScreenHighscore.cs @@ -239,7 +239,7 @@ namespace Vocaluxe.Screens for (int round = 0; round < points.NumRounds; round++) { SPlayer player = points.GetPlayer(round, CGame.NumPlayer)[0]; - CDataBase.LoadScore(out _Scores[round], player); + CDataBase.LoadScore(out _Scores[round], player.SongID, player.GameMode); } } diff --git a/Vocaluxe/SongQueue/CSongQueue.cs b/Vocaluxe/SongQueue/CSongQueue.cs index b23f1288..d11aeb4c 100644 --- a/Vocaluxe/SongQueue/CSongQueue.cs +++ b/Vocaluxe/SongQueue/CSongQueue.cs @@ -123,9 +123,7 @@ namespace Vocaluxe.SongQueue _CurrentSong, _SongQueue[_CurrentSong].SongID, players, - _SongQueue[_CurrentSong].GameMode == EGameMode.TR_GAMEMODE_MEDLEY, - _SongQueue[_CurrentSong].GameMode == EGameMode.TR_GAMEMODE_DUET, - _SongQueue[_CurrentSong].GameMode == EGameMode.TR_GAMEMODE_SHORTSONG); + _SongQueue[_CurrentSong].GameMode); } _CurrentSong++; } diff --git a/VocaluxeLib/Game/CPoints.cs b/VocaluxeLib/Game/CPoints.cs index 00749b0f..7326ccf6 100644 --- a/VocaluxeLib/Game/CPoints.cs +++ b/VocaluxeLib/Game/CPoints.cs @@ -35,15 +35,13 @@ namespace VocaluxeLib.Game _Rounds[round, player].Points = 0f; _Rounds[round, player].PointsGoldenNotes = 0f; _Rounds[round, player].PointsLineBonus = 0f; - _Rounds[round, player].Medley = false; - _Rounds[round, player].Duet = false; - _Rounds[round, player].ShortSong = false; + _Rounds[round, player].GameMode = EGameMode.TR_GAMEMODE_NORMAL; _Rounds[round, player].SongFinished = false; } } } - public void SetPoints(int round, int songID, SPlayer[] players, bool medley, bool duet, bool shortSong) + public void SetPoints(int round, int songID, SPlayer[] players, EGameMode gameMode) { long dateTicks = DateTime.Now.Ticks; for (int player = 0; player < players.Length; player++) @@ -53,9 +51,7 @@ namespace VocaluxeLib.Game _Rounds[round, player].Points = players[player].Points; _Rounds[round, player].PointsGoldenNotes = players[player].PointsGoldenNotes; _Rounds[round, player].PointsLineBonus = players[player].PointsLineBonus; - _Rounds[round, player].Medley = medley; - _Rounds[round, player].Duet = duet; - _Rounds[round, player].ShortSong = shortSong; + _Rounds[round, player].GameMode = gameMode; _Rounds[round, player].DateTicks = dateTicks; _Rounds[round, player].SongFinished = players[player].SongFinished; } @@ -87,9 +83,7 @@ namespace VocaluxeLib.Game players[p].PointsLineBonus = _Rounds[round, p].PointsLineBonus; players[p].SongID = _Rounds[round, p].SongID; players[p].VoiceNr = _Rounds[round, p].VoiceNr; - players[p].Medley = _Rounds[round, p].Medley; - players[p].Duet = _Rounds[round, p].Duet; - players[p].ShortSong = _Rounds[round, p].ShortSong; + players[p].GameMode = _Rounds[round, p].GameMode; players[p].DateTicks = _Rounds[round, p].DateTicks; players[p].SongFinished = _Rounds[round, p].SongFinished; players[p].ProfileID = _Rounds[round, p].ProfileID; diff --git a/VocaluxeLib/Structs.cs b/VocaluxeLib/Structs.cs index 895d593b..13ee20ca 100644 --- a/VocaluxeLib/Structs.cs +++ b/VocaluxeLib/Structs.cs @@ -190,9 +190,7 @@ namespace VocaluxeLib public int CurrentNote; public int SongID; - public bool Medley; - public bool Duet; - public bool ShortSong; + public EGameMode GameMode; public long DateTicks; public bool SongFinished; } From c27ae20b771019be802c2554896c3b43f23c93d7 Mon Sep 17 00:00:00 2001 From: Flamefire Date: Fri, 27 Sep 2013 17:14:28 +0200 Subject: [PATCH 03/18] Change min/max in LineBase to use simpler LINQ query --- VocaluxeLib/Songs/CLineBase.cs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/VocaluxeLib/Songs/CLineBase.cs b/VocaluxeLib/Songs/CLineBase.cs index 0a819509..41d88909 100644 --- a/VocaluxeLib/Songs/CLineBase.cs +++ b/VocaluxeLib/Songs/CLineBase.cs @@ -63,15 +63,10 @@ namespace VocaluxeLib.Songs { get { - int min = int.MaxValue; - int max = int.MinValue; - foreach (T note in _Notes) - { - if (note.Tone < min) - min = note.Tone; - if (note.Tone > max) - max = note.Tone; - } + if (_Notes.Count == 0) + return 0; + int min = _Notes.Max(note => note.Tone); + int max = _Notes.Min(note => note.Tone); return min - (max - min) / 4; } From 074a1ba82dbfd61f8aa56491c67f441214ad5f20 Mon Sep 17 00:00:00 2001 From: Flamefire Date: Fri, 4 Oct 2013 23:02:54 +0200 Subject: [PATCH 04/18] Change signature of getDBScores --- Vocaluxe/Base/CDataBase.cs | 10 +++++----- Vocaluxe/Base/CGame.cs | 8 ++++---- Vocaluxe/Screens/CScreenHighscore.cs | 17 ++++++----------- 3 files changed, 15 insertions(+), 20 deletions(-) diff --git a/Vocaluxe/Base/CDataBase.cs b/Vocaluxe/Base/CDataBase.cs index ada2a0a6..888ea52d 100644 --- a/Vocaluxe/Base/CDataBase.cs +++ b/Vocaluxe/Base/CDataBase.cs @@ -247,21 +247,20 @@ namespace Vocaluxe.Base return lastInsertID; } - public static void LoadScore(out List scores, int songID, EGameMode gameMode) + public static List LoadScore(int songID, EGameMode gameMode) { + var scores = new List(); using (var connection = new SQLiteConnection()) { connection.ConnectionString = "Data Source=" + _HighscoreFilePath; - scores = new List(); - try { connection.Open(); } catch (Exception) { - return; + return scores; } using (var command = new SQLiteCommand(connection)) @@ -284,7 +283,7 @@ namespace Vocaluxe.Base int dataBaseSongID = _GetDataBaseSongID(songID, command); if (dataBaseSongID < 0) - return; + return scores; command.CommandText = "SELECT PlayerName, Score, Date, Difficulty, LineNr, id FROM Scores " + "WHERE [SongID] = @SongID AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " + @@ -315,6 +314,7 @@ namespace Vocaluxe.Base } } } + return scores; } private static void _IncreaseSongCounter(int dataBaseSongID, SQLiteCommand command) diff --git a/Vocaluxe/Base/CGame.cs b/Vocaluxe/Base/CGame.cs index c64eaabc..de97c5b0 100644 --- a/Vocaluxe/Base/CGame.cs +++ b/Vocaluxe/Base/CGame.cs @@ -149,14 +149,14 @@ namespace Vocaluxe.Base return _SongQueue.GetSong(); } - public static CSong GetSong(int num) + public static CSong GetSong(int round) { - return _SongQueue.GetSong(num); + return _SongQueue.GetSong(round); } - public static EGameMode GetGameMode(int num) + public static EGameMode GetGameMode(int round) { - return _SongQueue.GetGameMode(num); + return _SongQueue.GetGameMode(round); } public static int GetNumSongs() diff --git a/Vocaluxe/Screens/CScreenHighscore.cs b/Vocaluxe/Screens/CScreenHighscore.cs index 9a75c943..ab44c452 100644 --- a/Vocaluxe/Screens/CScreenHighscore.cs +++ b/Vocaluxe/Screens/CScreenHighscore.cs @@ -194,10 +194,6 @@ namespace Vocaluxe.Screens base.OnShow(); _Round = 0; _Pos = 0; - CPoints points = CGame.GetPoints(); - _Scores = new List[points.NumRounds]; - for (int i = 0; i < _Scores.Length; i++) - _Scores[i] = new List(); _NewEntryIDs.Clear(); _AddScoresToDB(); _LoadScores(); @@ -231,15 +227,14 @@ namespace Vocaluxe.Screens private void _LoadScores() { - CPoints points = CGame.GetPoints(); - if (points == null) - return; - _Pos = 0; - for (int round = 0; round < points.NumRounds; round++) + int rounds = CGame.NumRounds; + _Scores = new List[rounds]; + for (int round = 0; round < rounds; round++) { - SPlayer player = points.GetPlayer(round, CGame.NumPlayer)[0]; - CDataBase.LoadScore(out _Scores[round], player.SongID, player.GameMode); + int songID = CGame.GetSong(round).ID; + EGameMode gameMode = CGame.GetGameMode(round); + _Scores[round] = CDataBase.LoadScore(songID, gameMode); } } From e6d8cf3ad942fb81075fb739be5ee8ab8d7cbd0d Mon Sep 17 00:00:00 2001 From: Flamefire Date: Tue, 8 Oct 2013 17:26:38 +0200 Subject: [PATCH 05/18] Fix crash --- Vocaluxe/Base/CGame.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/Vocaluxe/Base/CGame.cs b/Vocaluxe/Base/CGame.cs index de97c5b0..d8ea972c 100644 --- a/Vocaluxe/Base/CGame.cs +++ b/Vocaluxe/Base/CGame.cs @@ -404,9 +404,6 @@ namespace Vocaluxe.Base } Players[p].SungLines.RemoveRange(deleteLine, Players[p].SungLines.Count - deleteLine); } - CSong song = GetSong(); - for (int i = 0; i < GetSong().Notes.Voices[0].Lines.Length; i++) - CLog.LogError((i + 1) + ". " + song.Notes.Voices[0].Lines[i].NoteCount + " - " + Players[0].SungLines[i].NoteCount); CSound.SetPosition(soundStream, time); CVideo.Skip(vidStream, time, GetSong().VideoGap); From 271772301df8a148c0c41107f204a320a3e28d74 Mon Sep 17 00:00:00 2001 From: Flamefire Date: Tue, 8 Oct 2013 18:01:08 +0200 Subject: [PATCH 06/18] Fix some bugs where round was actually roundNr Now round (0 based) is always used --- Vocaluxe/Base/CGame.cs | 2 +- Vocaluxe/Screens/CScreenHighscore.cs | 25 +++------ Vocaluxe/Screens/CScreenNames.cs | 12 ++--- Vocaluxe/Screens/CScreenScore.cs | 31 ++++++------ Vocaluxe/SongQueue/CSongQueue.cs | 76 ++++++++++++++++++---------- Vocaluxe/SongQueue/ISongQueue.cs | 12 ++--- VocaluxeLib/CHelper.cs | 9 ++++ 7 files changed, 92 insertions(+), 75 deletions(-) diff --git a/Vocaluxe/Base/CGame.cs b/Vocaluxe/Base/CGame.cs index d8ea972c..ada61872 100644 --- a/Vocaluxe/Base/CGame.cs +++ b/Vocaluxe/Base/CGame.cs @@ -131,7 +131,7 @@ namespace Vocaluxe.Base public static void NextRound() { - _SongQueue.NextRound(Players); + _SongQueue.StartNextRound(Players); } public static bool IsFinished() diff --git a/Vocaluxe/Screens/CScreenHighscore.cs b/Vocaluxe/Screens/CScreenHighscore.cs index ab44c452..411cd2cd 100644 --- a/Vocaluxe/Screens/CScreenHighscore.cs +++ b/Vocaluxe/Screens/CScreenHighscore.cs @@ -242,7 +242,7 @@ namespace Vocaluxe.Screens { _IsDuet = false; CPoints points = CGame.GetPoints(); - CSong song = CGame.GetSong(_Round + 1); + CSong song = CGame.GetSong(_Round); if (song == null) return; @@ -250,7 +250,7 @@ namespace Vocaluxe.Screens if (points.NumRounds > 1) _Texts[_TextSongName].Text += " (" + (_Round + 1) + "/" + points.NumRounds + ")"; - switch (CGame.GetGameMode(_Round + 1)) + switch (CGame.GetGameMode(_Round)) { case EGameMode.TR_GAMEMODE_NORMAL: _Texts[_TextSongMode].Text = "TR_GAMEMODE_NORMAL"; @@ -279,28 +279,15 @@ namespace Vocaluxe.Screens private void _ChangePos(int num) { - if (num > 0) - { - if (_Pos + num + _NumEntrys < _Scores[_Round].Count) - _Pos += num; - } - if (num < 0) - { - _Pos += num; - if (_Pos < 0) - _Pos = 0; - } + _Pos += num; + _Pos = _Pos.Clamp(0, _Scores[_Round].Count - 1); } private void _ChangeRound(int num) { CPoints points = CGame.GetPoints(); - if (_Round + num < points.NumRounds && _Round + num > -1) - _Round += num; - else if (_Round + num >= points.NumRounds) - _Round = points.NumRounds - 1; - else if (_Round + num < 0) - _Round = 0; + _Round += num; + _Round = _Round.Clamp(0, points.NumRounds - 1); _UpdateRound(); } diff --git a/Vocaluxe/Screens/CScreenNames.cs b/Vocaluxe/Screens/CScreenNames.cs index f1f548ab..6ad757c9 100644 --- a/Vocaluxe/Screens/CScreenNames.cs +++ b/Vocaluxe/Screens/CScreenNames.cs @@ -239,7 +239,7 @@ namespace Vocaluxe.Screens break; case Keys.F10: - if (CGame.GetNumSongs() == 1 && CGame.GetSong(1).IsDuet) + if (CGame.GetNumSongs() == 1 && CGame.GetSong(0).IsDuet) { CSelectSlide selectSlideDuetPart = _SelectSlides[_SelectSlideDuetPlayer[_SelectingFastPlayerNr - 1]]; selectSlideDuetPart.Selection = (selectSlideDuetPart.Selection + 1) % 2; @@ -603,12 +603,12 @@ namespace Vocaluxe.Screens CProfiles.GetAvatarTextureFromProfile(CGame.Players[i].ProfileID) : _OriginalPlayerAvatarTextures[i]; _Texts[_TextPlayer[i]].Text = CProfiles.GetPlayerName(CGame.Players[i].ProfileID, i + 1); - if (CGame.GetNumSongs() == 1 && CGame.GetSong(1).IsDuet) + if (CGame.GetNumSongs() == 1 && CGame.GetSong(0).IsDuet) { _SelectSlides[_SelectSlideDuetPlayer[i]].Clear(); _SelectSlides[_SelectSlideDuetPlayer[i]].Visible = i + 1 <= CGame.NumPlayer; - _SelectSlides[_SelectSlideDuetPlayer[i]].AddValue(CGame.GetSong(1).DuetPart1); - _SelectSlides[_SelectSlideDuetPlayer[i]].AddValue(CGame.GetSong(1).DuetPart2); + _SelectSlides[_SelectSlideDuetPlayer[i]].AddValue(CGame.GetSong(0).DuetPart1); + _SelectSlides[_SelectSlideDuetPlayer[i]].AddValue(CGame.GetSong(0).DuetPart2); _SelectSlides[_SelectSlideDuetPlayer[i]].Selection = i % 2; } else @@ -623,7 +623,7 @@ namespace Vocaluxe.Screens { for (int i = 0; i < CGame.NumPlayer; i++) { - if (CGame.GetNumSongs() == 1 && CGame.GetSong(1).IsDuet) + if (CGame.GetNumSongs() == 1 && CGame.GetSong(0).IsDuet) CGame.Players[i].VoiceNr = _SelectSlides[_SelectSlideDuetPlayer[i]].Selection; } @@ -652,7 +652,7 @@ namespace Vocaluxe.Screens if (_Texts["TextPlayer" + i].Text == "") _Texts["TextPlayer" + i].Text = CProfiles.GetPlayerName(-1, i); _Equalizers["EqualizerPlayer" + i].Visible = true; - if (CGame.GetNumSongs() == 1 && CGame.GetSong(1).IsDuet) + if (CGame.GetNumSongs() == 1 && CGame.GetSong(0).IsDuet) _SelectSlides["SelectSlideDuetPlayer" + i].Visible = true; } else diff --git a/Vocaluxe/Screens/CScreenScore.cs b/Vocaluxe/Screens/CScreenScore.cs index fac4c499..51cd0273 100644 --- a/Vocaluxe/Screens/CScreenScore.cs +++ b/Vocaluxe/Screens/CScreenScore.cs @@ -118,7 +118,8 @@ namespace Vocaluxe.Screens public override void OnShow() { base.OnShow(); - _Round = CGame.NumRounds > 1 ? 0 : 1; + //-1 --> Show average + _Round = CGame.NumRounds > 1 ? -1 : 0; _Points = CGame.GetPoints(); _SavePlayedSongs(); @@ -130,8 +131,8 @@ namespace Vocaluxe.Screens public override bool UpdateGame() { var players = new SPlayer[CGame.NumPlayer]; - if (_Round != 0) - players = _Points.GetPlayer(_Round - 1, CGame.NumPlayer); + if (_Round >= 0) + players = _Points.GetPlayer(_Round, CGame.NumPlayer); else { for (int i = 0; i < CGame.NumRounds; i++) @@ -263,7 +264,7 @@ namespace Vocaluxe.Screens { CSong song = null; var players = new SPlayer[CGame.NumPlayer]; - if (_Round != 0) + if (_Round >= 0) { song = CGame.GetSong(_Round); if (song == null) @@ -271,8 +272,8 @@ namespace Vocaluxe.Screens _Texts[_TextSong].Text = song.Artist + " - " + song.Title; if (_Points.NumRounds > 1) - _Texts[_TextSong].Text += " (" + _Round + "/" + _Points.NumRounds + ")"; - players = _Points.GetPlayer(_Round - 1, CGame.NumPlayer); + _Texts[_TextSong].Text += " (" + (_Round + 1) + "/" + _Points.NumRounds + ")"; + players = _Points.GetPlayer(_Round, CGame.NumPlayer); } else { @@ -386,16 +387,14 @@ namespace Vocaluxe.Screens private void _ChangeRound(int num) { - if ((_Round + num) <= _Points.NumRounds && (_Round + num > 0)) - { - _Round += num; - _UpdateRatings(); - } - else if (num < 0 && _Round == 1 && CGame.NumRounds > 1) - { - _Round = 0; - _UpdateRatings(); - } + if (_Points.NumRounds < 1) + return; + _Round += num; + _Round = _Round.Clamp(-1, _Points.NumRounds - 1); + if (_Round >= _Points.NumRounds) + _Round = _Points.NumRounds - 1; + + _UpdateRatings(); } private void _SavePlayedSongs() diff --git a/Vocaluxe/SongQueue/CSongQueue.cs b/Vocaluxe/SongQueue/CSongQueue.cs index d11aeb4c..3fb3169f 100644 --- a/Vocaluxe/SongQueue/CSongQueue.cs +++ b/Vocaluxe/SongQueue/CSongQueue.cs @@ -39,7 +39,7 @@ namespace Vocaluxe.SongQueue class CSongQueue : ISongQueue { private List _SongQueue; - private int _CurrentSong; + private int _CurrentRound; private CPoints _Points; #region Implementation @@ -52,9 +52,7 @@ namespace Vocaluxe.SongQueue public EGameMode GetCurrentGameMode() { - if (_CurrentSong >= 0 && _CurrentSong < _SongQueue.Count) - return _SongQueue[_CurrentSong].GameMode; - return EGameMode.TR_GAMEMODE_NORMAL; + return GetGameMode(_CurrentRound); } public bool AddVisibleSong(int visibleIndex, EGameMode gameMode) @@ -105,7 +103,7 @@ namespace Vocaluxe.SongQueue public void Reset() { - _CurrentSong = -1; + _CurrentRound = -1; } public void Start(SPlayer[] players) @@ -113,37 +111,51 @@ namespace Vocaluxe.SongQueue _Points = new CPoints(_SongQueue.Count, players); } - public void NextRound(SPlayer[] players) + public void StartNextRound(SPlayer[] players) { - if (_CurrentSong < _SongQueue.Count && _SongQueue.Count > 0) + if (IsFinished()) + return; + if (_CurrentRound > -1) { - if (_CurrentSong > -1) - { - _Points.SetPoints( - _CurrentSong, - _SongQueue[_CurrentSong].SongID, - players, - _SongQueue[_CurrentSong].GameMode); - } - _CurrentSong++; + _Points.SetPoints( + _CurrentRound, + _SongQueue[_CurrentRound].SongID, + players, + _SongQueue[_CurrentRound].GameMode); } + _CurrentRound++; } public bool IsFinished() { - return _CurrentSong == _SongQueue.Count || _SongQueue.Count == 0; + return _CurrentRound >= _SongQueue.Count || _SongQueue.Count == 0; } + /// + /// Get current round nr (1 ~ n) + /// + /// current round nr (1 ~ n) public int GetCurrentRoundNr() { - return _CurrentSong + 1; + return _CurrentRound + 1; } + /// + /// Returns current round + /// + /// Current round (0 based) + public int GetCurrentRound() + { + return _CurrentRound; + } + + /// + /// Get current song + /// + /// Song of current round or null if there is none/game finished public CSong GetSong() { - if (_CurrentSong >= 0 && _CurrentSong < _SongQueue.Count) - return CGameModes.Get(_SongQueue[_CurrentSong].GameMode).GetSong(_SongQueue[_CurrentSong].SongID); - return null; + return GetSong(_CurrentRound); } public int GetNumSongs() @@ -151,18 +163,28 @@ namespace Vocaluxe.SongQueue return _SongQueue.Count; } - public CSong GetSong(int num) + /// + /// Get song of specified round + /// + /// Round (0 based) + /// Current song or null if out of bounds + public CSong GetSong(int round) { - if (num - 1 < _SongQueue.Count && num > 0) - return CSongs.GetSong(_SongQueue[num - 1].SongID); + if (round < _SongQueue.Count && round >= 0) + return CSongs.GetSong(_SongQueue[round].SongID); return null; } - public EGameMode GetGameMode(int num) + /// + /// Get gameMode of specified round + /// + /// Round (0 based) + /// Current song or null if out of bounds + public EGameMode GetGameMode(int round) { - if (num - 1 < _SongQueue.Count && num > 0) - return _SongQueue[num - 1].GameMode; + if (round < _SongQueue.Count && round >= 0) + return _SongQueue[round].GameMode; return EGameMode.TR_GAMEMODE_NORMAL; } diff --git a/Vocaluxe/SongQueue/ISongQueue.cs b/Vocaluxe/SongQueue/ISongQueue.cs index c3e32f45..1831fd74 100644 --- a/Vocaluxe/SongQueue/ISongQueue.cs +++ b/Vocaluxe/SongQueue/ISongQueue.cs @@ -25,8 +25,6 @@ namespace Vocaluxe.SongQueue { void Init(); - EGameMode GetCurrentGameMode(); - bool AddVisibleSong(int visibleIndex, EGameMode gameMode); bool AddSong(int absoluteIndex, EGameMode gameMode); bool RemoveVisibleSong(int visibleIndex); @@ -35,15 +33,17 @@ namespace Vocaluxe.SongQueue void Reset(); void Start(SPlayer[] players); - void NextRound(SPlayer[] players); + void StartNextRound(SPlayer[] players); bool IsFinished(); - int GetCurrentRoundNr(); CPoints GetPoints(); int GetNumSongs(); + int GetCurrentRoundNr(); + CSong GetSong(); - CSong GetSong(int num); - EGameMode GetGameMode(int num); + CSong GetSong(int round); + EGameMode GetCurrentGameMode(); + EGameMode GetGameMode(int round); } } \ No newline at end of file diff --git a/VocaluxeLib/CHelper.cs b/VocaluxeLib/CHelper.cs index ad04b6db..04ea1a90 100644 --- a/VocaluxeLib/CHelper.cs +++ b/VocaluxeLib/CHelper.cs @@ -47,6 +47,15 @@ namespace VocaluxeLib return (int)result; } + public static T Clamp(this T val, T min, T max) where T : IComparable + { + if (val.CompareTo(min) < 0) + return min; + if (val.CompareTo(max) > 0) + return max; + return val; + } + /// /// Concat strings into one string with ", " as separator. /// From f97547693340521b812ff6bc9bd153a28224b16c Mon Sep 17 00:00:00 2001 From: Flamefire Date: Mon, 21 Oct 2013 16:15:27 +0200 Subject: [PATCH 07/18] Fix typo --- VocaluxeLib/Songs/CLineBase.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/VocaluxeLib/Songs/CLineBase.cs b/VocaluxeLib/Songs/CLineBase.cs index 08297651..658b71de 100644 --- a/VocaluxeLib/Songs/CLineBase.cs +++ b/VocaluxeLib/Songs/CLineBase.cs @@ -65,8 +65,8 @@ namespace VocaluxeLib.Songs { if (_Notes.Count == 0) return 0; - int min = _Notes.Max(note => note.Tone); - int max = _Notes.Min(note => note.Tone); + int min = _Notes.Min(note => note.Tone); + int max = _Notes.Max(note => note.Tone); return min - (max - min) / 4; } From 24ca4edab77e08b81146cf338f13a8735fbaa390 Mon Sep 17 00:00:00 2001 From: Flamefire Date: Sun, 9 Mar 2014 19:49:06 +0100 Subject: [PATCH 08/18] Make Logfile more thread save --- Vocaluxe/Base/CLog.cs | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/Vocaluxe/Base/CLog.cs b/Vocaluxe/Base/CLog.cs index 6f87a74c..2dd153f0 100644 --- a/Vocaluxe/Base/CLog.cs +++ b/Vocaluxe/Base/CLog.cs @@ -28,6 +28,7 @@ namespace Vocaluxe.Base private readonly string _LogFileName; private readonly string _LogName; private StreamWriter _LogFile; + private Object _FileMutex = new Object(); public CLogFile(string fileName, string logName) { @@ -37,23 +38,31 @@ namespace Vocaluxe.Base private void _Open() { - _LogFile = new StreamWriter(Path.Combine(CSettings.DataPath, _LogFileName), false, Encoding.UTF8); + lock (_FileMutex) + { + if (_LogFile != null) + return; + _LogFile = new StreamWriter(Path.Combine(CSettings.DataPath, _LogFileName), false, Encoding.UTF8); - _LogFile.WriteLine(_LogName + " " + CSettings.GetFullVersionText() + " " + DateTime.Now); - _LogFile.WriteLine("----------------------------------------"); - _LogFile.WriteLine(); + _LogFile.WriteLine(_LogName + " " + CSettings.GetFullVersionText() + " " + DateTime.Now); + _LogFile.WriteLine("----------------------------------------"); + _LogFile.WriteLine(); + } } public void Close() { - if (_LogFile == null) - return; - try + lock (_FileMutex) { - _LogFile.Flush(); - _LogFile.Close(); + if (_LogFile == null) + return; + try + { + _LogFile.Flush(); + _LogFile.Close(); + } + catch (Exception) {} } - catch (Exception) {} } public void Add(string text) From 90ba1188d35e6302136eb483d0ad6e36c156edac Mon Sep 17 00:00:00 2001 From: Flamefire Date: Sun, 9 Mar 2014 20:07:28 +0100 Subject: [PATCH 09/18] Add more log files to distinguish between classes of messages --- Vocaluxe/Base/CLog.cs | 24 ++++++++++++++++++++---- Vocaluxe/Base/CMain.cs | 10 ++++++++++ Vocaluxe/Base/CSettings.cs | 2 ++ VocaluxeLib/IBasic.cs | 2 ++ VocaluxeLib/Songs/CSongLoader.cs | 2 +- 5 files changed, 35 insertions(+), 5 deletions(-) diff --git a/Vocaluxe/Base/CLog.cs b/Vocaluxe/Base/CLog.cs index 2dd153f0..740d958e 100644 --- a/Vocaluxe/Base/CLog.cs +++ b/Vocaluxe/Base/CLog.cs @@ -28,7 +28,7 @@ namespace Vocaluxe.Base private readonly string _LogFileName; private readonly string _LogName; private StreamWriter _LogFile; - private Object _FileMutex = new Object(); + private readonly Object _FileMutex = new Object(); public CLogFile(string fileName, string logName) { @@ -94,6 +94,8 @@ namespace Vocaluxe.Base private static CLogFile _ErrorLog; private static CLogFile _PerformanceLog; private static CLogFile _BenchmarkLog; + private static CLogFile _DebugLog; + private static CLogFile _SongInfoLog; private static int _NumErrors; private static Stopwatch[] _BenchmarkTimer; @@ -101,9 +103,11 @@ namespace Vocaluxe.Base public static void Init() { - _ErrorLog = new CLogFile(CSettings.FileErrorLog, "ErrorLog"); - _PerformanceLog = new CLogFile(CSettings.FilePerformanceLog, "PerformanceLog"); - _BenchmarkLog = new CLogFile(CSettings.FileBenchmarkLog, "BenchmarkLog"); + _ErrorLog = new CLogFile(CSettings.FileErrorLog, "Error-Log"); + _PerformanceLog = new CLogFile(CSettings.FilePerformanceLog, "Performance-Log"); + _BenchmarkLog = new CLogFile(CSettings.FileBenchmarkLog, "Benchmark-Log"); + _DebugLog = new CLogFile(CSettings.FileDebugLog, "Debug-Log"); + _SongInfoLog = new CLogFile(CSettings.FileSongInfoLog, "Song-Information-Log"); _NumErrors = 0; _BenchmarkTimer = new Stopwatch[_MaxBenchmarks]; @@ -116,6 +120,8 @@ namespace Vocaluxe.Base _ErrorLog.Close(); _PerformanceLog.Close(); _BenchmarkLog.Close(); + _DebugLog.Close(); + _SongInfoLog.Close(); } #region LogError @@ -132,6 +138,16 @@ namespace Vocaluxe.Base } #endregion LogError + public static void LogDebug(string text) + { + _DebugLog.Add(String.Format("{0:HH:mm:ss.ffff}", DateTime.Now) + ":" + text); + } + + public static void LogSongInfo(string text) + { + _SongInfoLog.Add(text); + } + #region LogPerformance public static void LogPerformance(string text) { diff --git a/Vocaluxe/Base/CMain.cs b/Vocaluxe/Base/CMain.cs index fad6fe07..e0f02c3d 100644 --- a/Vocaluxe/Base/CMain.cs +++ b/Vocaluxe/Base/CMain.cs @@ -443,6 +443,16 @@ namespace Vocaluxe.Base { CLog.LogError(errorText); } + + public void LogDebug(string text) + { + CLog.LogDebug(text); + } + + public void LogSongInfo(string text) + { + CLog.LogSongInfo(text); + } } class CBfonts : IFonts diff --git a/Vocaluxe/Base/CSettings.cs b/Vocaluxe/Base/CSettings.cs index e70a0d0c..e9dd805d 100644 --- a/Vocaluxe/Base/CSettings.cs +++ b/Vocaluxe/Base/CSettings.cs @@ -85,6 +85,8 @@ namespace Vocaluxe.Base public const string FilePerformanceLog = "Performance.log"; public const string FileErrorLog = "Error.log"; public const string FileBenchmarkLog = "Benchmark.log"; + public const string FileDebugLog = "Debug.log"; + public const string FileSongInfoLog = "SongInformation.log"; public const string SoundT440 = "440Hz.mp3"; diff --git a/VocaluxeLib/IBasic.cs b/VocaluxeLib/IBasic.cs index 682597b4..334221a0 100644 --- a/VocaluxeLib/IBasic.cs +++ b/VocaluxeLib/IBasic.cs @@ -155,6 +155,8 @@ namespace VocaluxeLib public interface ILog { void LogError(string errorText); + void LogDebug(string text); + void LogSongInfo(string text); } public interface IFonts diff --git a/VocaluxeLib/Songs/CSongLoader.cs b/VocaluxeLib/Songs/CSongLoader.cs index 98ba075c..8c959583 100644 --- a/VocaluxeLib/Songs/CSongLoader.cs +++ b/VocaluxeLib/Songs/CSongLoader.cs @@ -81,7 +81,7 @@ namespace VocaluxeLib.Songs msg = (error ? "Error: " : "Warning: ") + msg; if (withLineNr) msg += " in line #" + _LineNr; - CBase.Log.LogError(msg + " (" + Path.Combine(_Song.Folder, _Song.FileName) + ")"); + CBase.Log.LogSongInfo(msg + " (" + Path.Combine(_Song.Folder, _Song.FileName) + ")"); } private void _LogError(string msg, bool withLineNr = true) From 5787839b95ed13db7413e07777568a18c6e80f75 Mon Sep 17 00:00:00 2001 From: Flamefire Date: Mon, 10 Mar 2014 20:04:03 +0100 Subject: [PATCH 10/18] Introduce class for error log --- Vocaluxe/Base/CLog.cs | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/Vocaluxe/Base/CLog.cs b/Vocaluxe/Base/CLog.cs index 740d958e..8afe6cd4 100644 --- a/Vocaluxe/Base/CLog.cs +++ b/Vocaluxe/Base/CLog.cs @@ -65,7 +65,7 @@ namespace Vocaluxe.Base } } - public void Add(string text) + public virtual void Add(string text) { if (_LogFile == null) _Open(); @@ -78,15 +78,28 @@ namespace Vocaluxe.Base public void Dispose() { - if (_LogFile != null) - { - _LogFile.Dispose(); - _LogFile = null; - } + Close(); GC.SuppressFinalize(this); } } + class CErrorLogFile : CLogFile + { + private int _NumErrors; + private readonly Object _WriteMutex = new Object(); + + public CErrorLogFile(string fileName, string logName) : base(fileName, logName) {} + + public override void Add(string errorText) + { + lock (_WriteMutex) + { + _NumErrors++; + base.Add(_NumErrors + ") " + errorText); + } + } + } + static class CLog { private const int _MaxBenchmarks = 10; @@ -97,19 +110,17 @@ namespace Vocaluxe.Base private static CLogFile _DebugLog; private static CLogFile _SongInfoLog; - private static int _NumErrors; private static Stopwatch[] _BenchmarkTimer; private static readonly double _NanosecPerTick = (1000.0 * 1000.0 * 1000.0) / Stopwatch.Frequency; public static void Init() { - _ErrorLog = new CLogFile(CSettings.FileErrorLog, "Error-Log"); + _ErrorLog = new CErrorLogFile(CSettings.FileErrorLog, "Error-Log"); _PerformanceLog = new CLogFile(CSettings.FilePerformanceLog, "Performance-Log"); _BenchmarkLog = new CLogFile(CSettings.FileBenchmarkLog, "Benchmark-Log"); _DebugLog = new CLogFile(CSettings.FileDebugLog, "Debug-Log"); _SongInfoLog = new CLogFile(CSettings.FileSongInfoLog, "Song-Information-Log"); - _NumErrors = 0; _BenchmarkTimer = new Stopwatch[_MaxBenchmarks]; for (int i = 0; i < _BenchmarkTimer.Length; i++) _BenchmarkTimer[i] = new Stopwatch(); @@ -127,12 +138,11 @@ namespace Vocaluxe.Base #region LogError public static void LogError(string errorText, bool show = false, bool exit = false, Exception e = null) { - _NumErrors++; if (show) MessageBox.Show(errorText, CSettings.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Error); if (e != null) errorText += ": " + e; - _ErrorLog.Add(_NumErrors + ") " + errorText); + _ErrorLog.Add(errorText); if (exit) Environment.Exit(Environment.ExitCode); } @@ -148,13 +158,11 @@ namespace Vocaluxe.Base _SongInfoLog.Add(text); } - #region LogPerformance public static void LogPerformance(string text) { _PerformanceLog.Add(text); _PerformanceLog.Add("-------------------------------"); } - #endregion LogPerformance #region LogBenchmark public static void StartBenchmark(int benchmarkNr, string text) From 5b478a185e87d1775e8b9d9e4e2cc27902f2d515 Mon Sep 17 00:00:00 2001 From: Flamefire Date: Mon, 10 Mar 2014 21:13:03 +0100 Subject: [PATCH 11/18] Remove pointless Timer Make GetPlayerColor more consistent --- Vocaluxe/Base/CTheme.cs | 13 ++----------- Vocaluxe/Screens/CScreenLoad.cs | 11 ----------- 2 files changed, 2 insertions(+), 22 deletions(-) diff --git a/Vocaluxe/Base/CTheme.cs b/Vocaluxe/Base/CTheme.cs index 52bbc631..42b1bf7e 100644 --- a/Vocaluxe/Base/CTheme.cs +++ b/Vocaluxe/Base/CTheme.cs @@ -789,14 +789,8 @@ namespace Vocaluxe.Base public static SColorF GetPlayerColor(int playerNr) { - var color = new SColorF(1f, 1f, 1f, 1f); - - int skinIndex = GetSkinIndex(-1); - - if (_Skins[skinIndex].ThemeColors.Player.Length < playerNr) - return color; - - return _Skins[skinIndex].ThemeColors.Player[playerNr - 1]; + bool dummy; + return GetPlayerColor(playerNr, out dummy); } public static SColorF GetPlayerColor(string playerNrString) @@ -823,9 +817,6 @@ namespace Vocaluxe.Base { success = false; - if (_Skins[skinIndex].PartyModeID != -1) - skinIndex = GetSkinIndex(-1); - if (_Skins[skinIndex].ThemeColors.Player.Length < playerNr || playerNr < 1) return new SColorF(1f, 1f, 1f, 1f); diff --git a/Vocaluxe/Screens/CScreenLoad.cs b/Vocaluxe/Screens/CScreenLoad.cs index e5ccaae2..35ce9d38 100644 --- a/Vocaluxe/Screens/CScreenLoad.cs +++ b/Vocaluxe/Screens/CScreenLoad.cs @@ -15,7 +15,6 @@ // along with Vocaluxe. If not, see . #endregion -using System.Diagnostics; using System.Threading; using System.Windows.Forms; using Vocaluxe.Base; @@ -38,7 +37,6 @@ namespace Vocaluxe.Screens private readonly string[] _IntroVideo = new string[] {"IntroIn", "IntroMid", "IntroOut"}; private Thread _SongLoaderThread; - private Stopwatch _Timer; private bool _SkipIntro; private int _CurrentIntroVideoNr; private bool _IntroOutPlayed; @@ -54,7 +52,6 @@ namespace Vocaluxe.Screens _Intros = new CVideoPlayer[_IntroVideo.Length]; for (int i = 0; i < _Intros.Length; i++) _Intros[i] = new CVideoPlayer(); - _Timer = new Stopwatch(); } public override bool HandleInput(SKeyEvent keyEvent) @@ -135,7 +132,6 @@ namespace Vocaluxe.Screens CLog.StartBenchmark(0, "Load Songs Full"); _SongLoaderThread.IsBackground = true; _SongLoaderThread.Start(); - _Timer.Start(); if (CConfig.BackgroundMusic == EOffOn.TR_CONFIG_ON && CConfig.BackgroundMusicSource == EBackgroundMusicSource.TR_CONFIG_NO_OWN_MUSIC && !_BGMusicStarted) @@ -155,11 +151,6 @@ namespace Vocaluxe.Screens { _CheckStartIntroVideos(); - if (CSettings.GameState == EGameState.EditTheme) - _Timer.Stop(); - else - _Timer.Start(); - bool next = CConfig.CoverLoading != ECoverLoading.TR_CONFIG_COVERLOADING_ATSTART || CSongs.CoverLoaded; if ((_IntroOutPlayed || _SkipIntro) && next && CSettings.GameState != EGameState.EditTheme && CSongs.SongsLoaded) @@ -201,8 +192,6 @@ namespace Vocaluxe.Screens public override void OnClose() { base.OnClose(); - _Timer.Stop(); - _Timer.Reset(); foreach (CVideoPlayer videoPlayer in _Intros) videoPlayer.Close(); From 070777eb68ef590ab53b1a890ab94586a59609ae Mon Sep 17 00:00:00 2001 From: Flamefire Date: Mon, 10 Mar 2014 21:13:28 +0100 Subject: [PATCH 12/18] Show the color of a player while selecting channels --- .../Ambient/Screens/ScreenOptionsRecord.xml | 66 +++++++++---------- .../Changelog_ScreenOptionsRecord.txt | 5 +- Vocaluxe/Screens/CScreenOptionsRecord.cs | 18 +++-- 3 files changed, 51 insertions(+), 38 deletions(-) diff --git a/Output/Themes/Ambient/Screens/ScreenOptionsRecord.xml b/Output/Themes/Ambient/Screens/ScreenOptionsRecord.xml index b2620651..ba0ce824 100644 --- a/Output/Themes/Ambient/Screens/ScreenOptionsRecord.xml +++ b/Output/Themes/Ambient/Screens/ScreenOptionsRecord.xml @@ -1,7 +1,7 @@  - 3 + 4 Video @@ -216,6 +216,35 @@ + + 75 + 347 + + 0,00 + + 27 + + + + StaticColor + + + TextSColor + + Left + + Center + + + + Outline + + TR_SCREENORECORD_MIC_DELAY + + + + + 75 227 @@ -243,8 +272,8 @@ - - + + 75 287 @@ -272,36 +301,7 @@ - - - - 75 - 347 - - 0,00 - - 27 - - - - StaticColor - - - TextSColor - - Left - - Center - - - - Outline - - TR_SCREENORECORD_MIC_DELAY - - - - + 640 diff --git a/Output/Themes/Changelog/Changelog_ScreenOptionsRecord.txt b/Output/Themes/Changelog/Changelog_ScreenOptionsRecord.txt index 89d9465c..1eb9f362 100644 --- a/Output/Themes/Changelog/Changelog_ScreenOptionsRecord.txt +++ b/Output/Themes/Changelog/Changelog_ScreenOptionsRecord.txt @@ -6,4 +6,7 @@ Version 2: Add: and . This is a new theme-element. Check ScreenOptionsRecord.xml for style-possibilities. -++++++++++ \ No newline at end of file +++++++++++ +Version 4: +Rename Text 3/4 to TextChannel1/2 +Rename Text5 to Text3 \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsRecord.cs b/Vocaluxe/Screens/CScreenOptionsRecord.cs index 3d8bdbf8..6adc9bd5 100644 --- a/Vocaluxe/Screens/CScreenOptionsRecord.cs +++ b/Vocaluxe/Screens/CScreenOptionsRecord.cs @@ -37,7 +37,7 @@ namespace Vocaluxe.Screens // Version number for theme files. Increment it, if you've changed something on the theme files! protected override int _ScreenVersion { - get { return 3; } + get { return 4; } } private const float _MaxDelayTime = 1f; @@ -53,6 +53,9 @@ namespace Vocaluxe.Screens private const string _ButtonExit = "ButtonExit"; private const string _ButtonDelayTest = "ButtonDelayTest"; + private const string _TextChannel1 = "TextChannel1"; + private const string _TextChannel2 = "TextChannel2"; + private const string _TextDelayChannel1 = "TextDelayChannel1"; private const string _TextDelayChannel2 = "TextDelayChannel2"; @@ -77,7 +80,7 @@ namespace Vocaluxe.Screens values.AddRange(_StaticEnergyChannel); _ThemeStatics = values.ToArray(); - _ThemeTexts = new string[] {_TextWarning, _TextDelayChannel1, _TextDelayChannel2}; + _ThemeTexts = new string[] {_TextWarning, _TextChannel1, _TextChannel2, _TextDelayChannel1, _TextDelayChannel2}; _ThemeButtons = new string[] {_ButtonExit, _ButtonDelayTest}; _ThemeSelectSlides = new string[] {_SelectSlideRecordDevices, _SelectSlideRecordChannel1, _SelectSlideRecordChannel2, _SelectSlideDelay}; _ThemeEqualizers = new string[] {_EqualizerChannel1, _EqualizerChannel2}; @@ -248,8 +251,7 @@ namespace Vocaluxe.Screens _DelayTest[i].Timer.Stop(); _DelayTestRunning = false; } - else if (CSound.RecordGetMaxVolume(player - 1) > 0.1f && - (CSound.RecordGetToneAbs(player - 1) == 9 || CSound.RecordGetToneAbs(player - 1) == 21 || CSound.RecordGetToneAbs(player - 1) == 33)) + else if (CSound.RecordGetMaxVolume(player - 1) > 0.1f && CSound.RecordGetToneAbs(player - 1) % 12 == 9) { _DelayTest[i].Delay = _DelayTest[i].Timer.ElapsedMilliseconds; _DelayTest[i].Timer.Stop(); @@ -444,6 +446,12 @@ namespace Vocaluxe.Screens CSound.RecordStart(); } + private void _SetPlayerColors() + { + _Texts[_TextChannel1].Color = CTheme.GetPlayerColor(_SelectSlides[_SelectSlideRecordChannel1].Selection); + _Texts[_TextChannel2].Color = CTheme.GetPlayerColor(_SelectSlides[_SelectSlideRecordChannel2].Selection); + } + private void _SetMicConfig() { if (_DeviceNr < 0) @@ -451,6 +459,7 @@ namespace Vocaluxe.Screens CRecordDevice device = _Devices[_DeviceNr]; device.PlayerChannel1 = _SelectSlides[_SelectSlideRecordChannel1].Selection; device.PlayerChannel2 = _SelectSlides[_SelectSlideRecordChannel2].Selection; + _SetPlayerColors(); } private void _UpdateChannels() @@ -459,6 +468,7 @@ namespace Vocaluxe.Screens _SelectSlides[_SelectSlideRecordChannel2].Selection = _Devices[_DeviceNr].PlayerChannel2; _SaveMicConfig(); + _SetPlayerColors(); } private bool _CheckMicConfig() From 0a9c6e5cfedc0eb26c0dd532a5a8db01b702959b Mon Sep 17 00:00:00 2001 From: Flamefire Date: Tue, 11 Mar 2014 00:42:22 +0100 Subject: [PATCH 13/18] Make the Serverconfig request admin rights only if required --- ClientServerLib/ClientServerLib/CServer.cs | 10 +- Vocaluxe/Program.cs | 2 + WebserverInitalConfig/CConfigHttpApi.cs | 204 +++++++++++++----- WebserverInitalConfig/Program.cs | 58 +++-- .../WebserverInitalConfig.csproj | 3 - 5 files changed, 206 insertions(+), 71 deletions(-) diff --git a/ClientServerLib/ClientServerLib/CServer.cs b/ClientServerLib/ClientServerLib/CServer.cs index ab704a95..51a6d2b7 100644 --- a/ClientServerLib/ClientServerLib/CServer.cs +++ b/ClientServerLib/ClientServerLib/CServer.cs @@ -142,14 +142,14 @@ namespace ServerLib smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb);*/ - _RegisterUrlAndCert(_BaseAddress.Port); + _RegisterUrlAndCert(_BaseAddress.Port, false); _Host.Open(); } catch (CommunicationException e) { if (e is AddressAccessDeniedException || e is AddressAlreadyInUseException) { - _RegisterUrlAndCert(_BaseAddress.Port); + _RegisterUrlAndCert(_BaseAddress.Port, true); try { _Host.Abort(); @@ -178,18 +178,18 @@ namespace ServerLib } } - private void _RegisterUrlAndCert(int port) + private void _RegisterUrlAndCert(int port, bool reserve) { #if WIN ProcessStartInfo info = new ProcessStartInfo { FileName = "VocaluxeServerConfig.exe", - Arguments = port + " " + (_Encrypted ? "true" : "false"), + WorkingDirectory = Environment.CurrentDirectory, + Arguments = port + " " + (_Encrypted ? "true" : "false") + (reserve ? " reserve" : ""), UseShellExecute = true, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, - Verb = "runas" }; Process p = Process.Start(info); p.WaitForExit(); diff --git a/Vocaluxe/Program.cs b/Vocaluxe/Program.cs index 5d254c13..b59d4f9e 100644 --- a/Vocaluxe/Program.cs +++ b/Vocaluxe/Program.cs @@ -259,6 +259,7 @@ namespace Vocaluxe Environment.Exit(Environment.ExitCode); } +#if !DEBUG [HandleProcessCorruptedStateExceptions] private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args) { @@ -273,6 +274,7 @@ namespace Vocaluxe CLog.LogError("Unhandled exception: " + e.Message + stackTrace); _CloseProgram(); } +#endif private static Assembly _AssemblyResolver(Object sender, ResolveEventArgs args) { diff --git a/WebserverInitalConfig/CConfigHttpApi.cs b/WebserverInitalConfig/CConfigHttpApi.cs index 4bbd3ed9..fe184af4 100644 --- a/WebserverInitalConfig/CConfigHttpApi.cs +++ b/WebserverInitalConfig/CConfigHttpApi.cs @@ -15,6 +15,9 @@ // along with Vocaluxe. If not, see . #endregion +using System.Diagnostics; +using System.Security.Authentication; +using System.Security.Principal; using Security.Cryptography; using Security.Cryptography.X509Certificates; using System; @@ -26,34 +29,64 @@ using NetFwTypeLib; namespace WebserverInitalConfig { - public static class CConfigHttpApi + public class CConfigHttpApi { // ReSharper disable InconsistentNaming private const String CLSID_NetFwMgr = "{304CE942-6E39-40D8-943A-B913C40C9CD4}"; private const String CLSID_NetAuthApp = "{EC9846B3-2762-4A6B-A214-6ACB603462D2}"; private const String CLSID_NetOpenPort = "{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}"; + private const string _AppGUID = "{7baf41f1-48b7-42cb-b145-f815499cb48f}"; // ReSharper restore InconsistentNaming - public static void ReserveUrl(string networkString) + + private readonly string _RuleName; + private readonly string _ExePath; + private readonly string _IP; + private readonly int _Port; + private readonly bool _IsTCP; + + public CConfigHttpApi(string ruleName, string exePath, string ip, int port, bool isTCP) { + _ExePath = exePath; + _Port = port; + _IsTCP = isTCP; + _IP = ip; + _RuleName = ruleName; + } + + private static void _ReserveUrl(string networkString) + { + if (!IsAdministrator()) + throw new AuthenticationException(); HttpApi.ReserveURL(networkString, "D:(A;;GX;;;S-1-1-0)"); } - public static void BindCert(string ip, int port, X509Certificate2 cert) + public void ReserveUrl() { - IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(ip), port); - if (HttpApi.QuerySslCertificateInfo(endpoint) != null) - HttpApi.DeleteCertificateBinding(endpoint); - - HttpApi.BindCertificate(endpoint, cert.GetCertHash(), StoreName.My, new Guid("{7baf41f1-48b7-42cb-b145-f815499cb48f}")); + _ReserveUrl("https://+:" + _Port + "/"); } - public static void AddCertToStore(X509Certificate2 cert) + private void _BindCert(X509Certificate cert) + { + IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(_IP), _Port); + HttpApi.SslCertificateInfo certificateInfo = HttpApi.QuerySslCertificateInfo(endpoint); + if (certificateInfo != null && !certificateInfo.Hash.SequenceEqual(cert.GetCertHash())) + { + if (!IsAdministrator()) + throw new AuthenticationException(); + HttpApi.DeleteCertificateBinding(endpoint); + + HttpApi.BindCertificate(endpoint, cert.GetCertHash(), StoreName.My, new Guid(_AppGUID)); + } + } + + private static void _AddCertToStore(X509Certificate2 cert) { X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); - X509Certificate2Collection oldCerts = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, - cert.SubjectName.Name, false); + // ReSharper disable AssignNullToNotNullAttribute + X509Certificate2Collection oldCerts = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.SubjectName.Name, false); + // ReSharper restore AssignNullToNotNullAttribute foreach (X509Certificate2 oldCert in oldCerts) store.Remove(oldCert); @@ -62,7 +95,25 @@ namespace WebserverInitalConfig store.Close(); } - public static X509Certificate2 GetSelfSignedCert(string subjectName) + private static X509Certificate2 _GetCert(string name) + { + X509Certificate2 result = null; + X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); + store.Open(OpenFlags.ReadOnly); + + var name2 = new X500DistinguishedName(name); + // ReSharper disable AssignNullToNotNullAttribute + X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, name2.Name, false); + // ReSharper restore AssignNullToNotNullAttribute + if (certs.Count > 0) + result = certs[0]; + + store.Close(); + + return result; + } + + private X509Certificate2 _GetSelfSignedCert(string subjectName) { var keyParam = new CngKeyCreationParameters { @@ -91,58 +142,113 @@ namespace WebserverInitalConfig byte[] rawData = key.CreateSelfSignedCertificate(param).Export(X509ContentType.Pfx, ""); var cert = new X509Certificate2(rawData, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet) { - FriendlyName = "Vocaluxe Server Certificate" + FriendlyName = _RuleName + " Server Certificate" }; return cert; } - private static void _AddFirewallRuleForProfile(INetFwProfile profile, string exePath, int port, bool isTCP) + public void CreateAndAddCert(string hostName) { - bool isFirewallEnabled = profile.FirewallEnabled; + string certName = "CN=" + hostName + ", C=DE, O=" + _RuleName + ", OU=" + _RuleName + " Server"; - if (!isFirewallEnabled) - return; - INetFwAuthorizedApplications applications = profile.AuthorizedApplications; - if (!(from INetFwAuthorizedApplication a in applications - where a.ProcessImageFileName == exePath - select a).Any()) + X509Certificate2 cert = _GetCert(certName); + if (cert == null) { - INetFwAuthorizedApplication application = (INetFwAuthorizedApplication)Activator.CreateInstance( - Type.GetTypeFromCLSID(new Guid(CLSID_NetAuthApp))); - - application.Name = "Vocaluxe"; - application.ProcessImageFileName = exePath; - application.Enabled = true; - application.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL; - applications.Add(application); - } - INetFwOpenPorts openPorts = profile.GloballyOpenPorts; - NET_FW_IP_PROTOCOL_ protocol = isTCP ? NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP : NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; - if (!(from INetFwOpenPort p in openPorts - where (p.Port == port && - (p.Protocol == protocol)) - select p).Any()) - { - INetFwOpenPort openPort = (INetFwOpenPort)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSID_NetOpenPort))); - openPort.Enabled = true; - openPort.Port = port; - openPort.Protocol = protocol; - openPort.Name = "Vocaluxe(" + port + ")"; - openPort.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL; - - openPorts.Add(openPort); + if (!IsAdministrator()) + throw new AuthenticationException(); + cert = _GetSelfSignedCert(certName); + _AddCertToStore(cert); } + _BindCert(cert); } - public static void AddFirewallRule(string exePath, int port, bool isTCP) + private bool _IsAppAuthorized(INetFwProfile profile) + { + if (!profile.FirewallEnabled) + return true; + foreach (INetFwAuthorizedApplication a in profile.AuthorizedApplications) + { + if (a.ProcessImageFileName == _ExePath) + return true; + } + return false; + } + + private bool _IsPortOpen(INetFwProfile profile) + { + NET_FW_IP_PROTOCOL_ protocol = _GetProtocol(); + + if (!profile.FirewallEnabled) + return true; + foreach (INetFwOpenPort p in profile.GloballyOpenPorts) + { + if (p.Protocol == protocol && p.Port == _Port) + return true; + } + return false; + } + + private NET_FW_IP_PROTOCOL_ _GetProtocol() + { + return _IsTCP ? NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP : NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; + } + + private void _AddFirewallRuleForProfile(INetFwProfile profile) + { + bool isAppAuthorized = _IsAppAuthorized(profile); + bool isPortOpen = _IsPortOpen(profile); + + if ((!isAppAuthorized || !isPortOpen) && !IsAdministrator()) + throw new AuthenticationException(); + if (!isAppAuthorized) + _AddAppToFirewall(profile); + + if (!isPortOpen) + _AddPortToFirewall(profile); + } + + private void _AddPortToFirewall(INetFwProfile profile) + { + INetFwOpenPort openPort = (INetFwOpenPort)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSID_NetOpenPort))); + openPort.Enabled = true; + openPort.Port = _Port; + openPort.Protocol = _GetProtocol(); + openPort.Name = _RuleName + "(" + _Port + ")"; + openPort.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL; + + profile.GloballyOpenPorts.Add(openPort); + } + + private void _AddAppToFirewall(INetFwProfile profile) + { + INetFwAuthorizedApplication application = (INetFwAuthorizedApplication)Activator.CreateInstance( + Type.GetTypeFromCLSID(new Guid(CLSID_NetAuthApp))); + + application.Name = _RuleName; + application.ProcessImageFileName = _ExePath; + application.Enabled = true; + application.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL; + profile.AuthorizedApplications.Add(application); + } + + public static bool IsAdministrator() + { + WindowsIdentity identity = WindowsIdentity.GetCurrent(); + // ReSharper disable AssignNullToNotNullAttribute + WindowsPrincipal principal = new WindowsPrincipal(identity); + // ReSharper restore AssignNullToNotNullAttribute + return principal.IsInRole(WindowsBuiltInRole.Administrator); + } + + public void AddFirewallRule() { INetFwMgr manage = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSID_NetFwMgr))); - //AddFirewallRuleForProfile(manage.LocalPolicy.CurrentProfile, exePath, port, isTCP); + //_AddFirewallRuleForProfile(manage.LocalPolicy.CurrentProfile); //if (manage.CurrentProfileType != NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_STANDARD) //Add to Home/Work(Private) and current net //TODO: This somewhow adds 2 entries each instead of only one that is activated for Home/Work and public nets - _AddFirewallRuleForProfile(manage.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_STANDARD), exePath, port, isTCP); - _AddFirewallRuleForProfile(manage.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_CURRENT), exePath, port, isTCP); + _AddFirewallRuleForProfile(manage.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_STANDARD)); + _AddFirewallRuleForProfile(manage.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_CURRENT)); } /*public static X509Certificate2 getCert(string subject) diff --git a/WebserverInitalConfig/Program.cs b/WebserverInitalConfig/Program.cs index 4b7ce630..a4f3a315 100644 --- a/WebserverInitalConfig/Program.cs +++ b/WebserverInitalConfig/Program.cs @@ -16,34 +16,64 @@ #endregion using System; +using System.Diagnostics; using System.IO; using System.Net; +using System.Net.Mime; +using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; namespace WebserverInitalConfig { - class Program + static class CProgram { + // ReSharper disable InconsistentNaming private static void Main(string[] args) + // ReSharper restore InconsistentNaming { - if (args.Length != 2) + int port; + if (args.Length < 2 || !int.TryParse(args[0], out port)) { Console.WriteLine("Usage: VocaluxeServerConfig port isHttps"); Environment.Exit(-1); } - - CConfigHttpApi.AddFirewallRule(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Vocaluxe.exe"), Int32.Parse(args[0]), true); - - if (args[1].ToLower() == "true") - { - string hostname = Dns.GetHostName(); - X509Certificate2 cert = CConfigHttpApi.GetSelfSignedCert("CN=" + hostname + " C=DE O=Vocaluxe OU=Vocaluxe Server"); - CConfigHttpApi.AddCertToStore(cert); - CConfigHttpApi.BindCert("0.0.0.0", Int32.Parse(args[0]), cert); - CConfigHttpApi.ReserveUrl("https://+:" + args[0] + "/"); - } else - CConfigHttpApi.ReserveUrl("http://+:" + args[0] + "/"); + { + CConfigHttpApi config = new CConfigHttpApi("Vocaluxe", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Vocaluxe.exe"), "0.0.0.0", port, true); + try + { + config.AddFirewallRule(); + if (args[1].ToLower() == "true") + config.CreateAndAddCert(Dns.GetHostName()); + + if ((args.Length >= 3 && args[2] == "reserve") || CConfigHttpApi.IsAdministrator()) + config.ReserveUrl(); + } + catch (AuthenticationException) + { + ProcessStartInfo proc = new ProcessStartInfo + { + UseShellExecute = true, + WorkingDirectory = Environment.CurrentDirectory, + FileName = Process.GetCurrentProcess().MainModule.FileName, + Arguments = args[0] + " " + args[1], + Verb = "runas", + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + }; + + try + { + Process.Start(proc); + } + catch + { + // The user refused the elevation. + // Do nothing and return directly ... + Environment.Exit(-1); + } + } + } } } } \ No newline at end of file diff --git a/WebserverInitalConfig/WebserverInitalConfig.csproj b/WebserverInitalConfig/WebserverInitalConfig.csproj index 7544f7a3..2f48f927 100644 --- a/WebserverInitalConfig/WebserverInitalConfig.csproj +++ b/WebserverInitalConfig/WebserverInitalConfig.csproj @@ -32,9 +32,6 @@ prompt 4 - - app.manifest - Vocaluxe.ico From 44dceaed60791d1fa480bc56c236e481ae9356de Mon Sep 17 00:00:00 2001 From: Flamefire Date: Tue, 11 Mar 2014 20:30:07 +0100 Subject: [PATCH 14/18] Add names to all threads --- ClientServerLib/ClientServerLib/CDiscover.cs | 2 +- Vocaluxe/Lib/Sound/CDirectSoundRecord.cs | 2 +- Vocaluxe/Lib/Sound/CGstreamerSharpAudio.cs | 31 ++++++++++++++++---- Vocaluxe/Lib/Sound/COpenALPlay.cs | 2 +- Vocaluxe/Lib/Sound/CPortAudioPlay.cs | 2 +- 5 files changed, 29 insertions(+), 10 deletions(-) diff --git a/ClientServerLib/ClientServerLib/CDiscover.cs b/ClientServerLib/ClientServerLib/CDiscover.cs index 9dd5aa3d..ecff0173 100644 --- a/ClientServerLib/ClientServerLib/CDiscover.cs +++ b/ClientServerLib/ClientServerLib/CDiscover.cs @@ -73,7 +73,7 @@ namespace ServerLib return; _DiscoverRunning = true; - _DiscoverThread = new Thread(() => _Discover(Timeout)); + _DiscoverThread = new Thread(() => _Discover(Timeout)) {Name = "Client discover"}; _OnDiscovered = OnDiscovered; _DiscoverThread.Start(); } diff --git a/Vocaluxe/Lib/Sound/CDirectSoundRecord.cs b/Vocaluxe/Lib/Sound/CDirectSoundRecord.cs index 15fcc291..a769fb5e 100644 --- a/Vocaluxe/Lib/Sound/CDirectSoundRecord.cs +++ b/Vocaluxe/Lib/Sound/CDirectSoundRecord.cs @@ -326,7 +326,7 @@ namespace Vocaluxe.Lib.Sound for (int i = 0; i < _Notifications.Count; i++) _WaitHandles[i] = _Notifications[i].Event; - _CaptureThread = new Thread(_DoCapture) {IsBackground = true}; + _CaptureThread = new Thread(_DoCapture) {Name="DirectSoundCapture",IsBackground = true}; _Running = true; _CaptureThread.Start(); diff --git a/Vocaluxe/Lib/Sound/CGstreamerSharpAudio.cs b/Vocaluxe/Lib/Sound/CGstreamerSharpAudio.cs index b8270b32..84e2226c 100644 --- a/Vocaluxe/Lib/Sound/CGstreamerSharpAudio.cs +++ b/Vocaluxe/Lib/Sound/CGstreamerSharpAudio.cs @@ -37,10 +37,10 @@ namespace Vocaluxe.Lib.Sound public bool Init() { #if ARCH_X86 - string path = ".\\x86\\gstreamer"; + const string path = ".\\x86\\gstreamer"; #endif #if ARCH_X64 - string path = ".\\x64\\gstreamer"; + const string path = ".\\x64\\gstreamer"; #endif SetDllDirectory(path); Application.Init(); @@ -213,9 +213,9 @@ namespace Vocaluxe.Lib.Sound private class CGstreamerSharpAudioStream { - private readonly Element _Element; + private Element _Element; private bool _Loop; - public volatile bool Closed; + public volatile bool Closed = true; public volatile bool Finished; private bool _Fading; @@ -240,7 +240,10 @@ namespace Vocaluxe.Lib.Sound var audioSinkBin = new Bin("Audiosink"); if (convert == null || audiosink == null) + { CLog.LogError("Could not create pipeline"); + return; + } audioSinkBin.Add(convert); audioSinkBin.Add(audiosink); @@ -249,21 +252,35 @@ namespace Vocaluxe.Lib.Sound GhostPad ghostpad = new GhostPad("sink", pad); if (pad == null) + { CLog.LogError("Could not create pads"); + return; + } if (!ghostpad.SetActive(true)) + { CLog.LogError("Could not link pads"); + return; + } if (!audioSinkBin.AddPad(ghostpad)) + { CLog.LogError("Could not add pad"); + return; + } _Element = ElementFactory.Make("playbin", "playbin"); if (_Element == null) + { CLog.LogError("Could not create playbin"); + return; + } _Element["audio-sink"] = audioSinkBin; _Element["flags"] = 1 << 1; _Element["uri"] = new Uri(media).AbsoluteUri; _Element.SetState(State.Paused); + Closed = false; //Enable stream + // Passing CLOCK_TIME_NONE here causes the pipeline to block for a long time so with // prescan enabled the pipeline will wait 500ms for stream to initialize and then continue // if it takes more than 500ms, duration queries will be performed asynchronously @@ -307,7 +324,7 @@ namespace Vocaluxe.Lib.Sound { Closed = true; Finished = true; - var t = new Thread(_TerminateStream); + var t = new Thread(_TerminateStream) {Name = "GSt Terminate"}; t.Start(); } } @@ -318,6 +335,7 @@ namespace Vocaluxe.Lib.Sound { _Element.SetState(State.Null); _Element.Dispose(); + _Element = null; } } @@ -388,7 +406,8 @@ namespace Vocaluxe.Lib.Sound { if (_Duration < 0 && !_QueryingDuration) { - var t = new Thread(_UpdateDuration); + _QueryingDuration = true; // Set this to avoid race conditions + var t = new Thread(_UpdateDuration) {Name = "GSt Update Duration"}; t.Start(); } return _Duration > 0 ? _Duration : -1; diff --git a/Vocaluxe/Lib/Sound/COpenALPlay.cs b/Vocaluxe/Lib/Sound/COpenALPlay.cs index caecc663..67891ffb 100644 --- a/Vocaluxe/Lib/Sound/COpenALPlay.cs +++ b/Vocaluxe/Lib/Sound/COpenALPlay.cs @@ -416,7 +416,7 @@ namespace Vocaluxe.Lib.Sound public COpenAlStream() { _Initialized = false; - _DecoderThread = new Thread(_Execute); + _DecoderThread = new Thread(_Execute) {Name = "OpenAL Decode"}; } public void Free(Closeproc closeProc, int streamID, Object closeMutex) diff --git a/Vocaluxe/Lib/Sound/CPortAudioPlay.cs b/Vocaluxe/Lib/Sound/CPortAudioPlay.cs index 6cbf218b..985d936e 100644 --- a/Vocaluxe/Lib/Sound/CPortAudioPlay.cs +++ b/Vocaluxe/Lib/Sound/CPortAudioPlay.cs @@ -401,7 +401,7 @@ namespace Vocaluxe.Lib.Sound public CPortAudioStream() { _SyncTimer = new CSyncTimer(0f, 1f, 0.02f); - _DecoderThread = new Thread(_Execute); + _DecoderThread = new Thread(_Execute) {Name = "PortAudio Decode"}; } ~CPortAudioStream() From 668d72d3a7339ce397ca0f68e158eaa9514dd402 Mon Sep 17 00:00:00 2001 From: Flamefire Date: Tue, 11 Mar 2014 21:50:33 +0100 Subject: [PATCH 15/18] Make WiiMote consume less resources (do not run thread if not required) --- Vocaluxe/Lib/Input/CHIDAPI.cs | 12 +- Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs | 17 +-- Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs | 163 ++++++++--------------- 3 files changed, 68 insertions(+), 124 deletions(-) diff --git a/Vocaluxe/Lib/Input/CHIDAPI.cs b/Vocaluxe/Lib/Input/CHIDAPI.cs index 3252373c..59d86148 100644 --- a/Vocaluxe/Lib/Input/CHIDAPI.cs +++ b/Vocaluxe/Lib/Input/CHIDAPI.cs @@ -161,25 +161,25 @@ namespace Vocaluxe.Lib.Input public static int ReadTimeout(IntPtr device, ref byte[] data, int length, int milliseconds) { IntPtr dataPtr = Marshal.AllocHGlobal(length); - int result; + int bytesRead; try { - result = hid_read_timeout(device, dataPtr, length, milliseconds); + bytesRead = hid_read_timeout(device, dataPtr, length, milliseconds); } catch (Exception e) { - result = -1; + bytesRead = -1; CLog.LogError("Error CHIDAPI.ReadTimeout(): " + e); } - if (result != -1) - Marshal.Copy(dataPtr, data, 0, result); + if (bytesRead != -1) + Marshal.Copy(dataPtr, data, 0, bytesRead); else data = null; Marshal.FreeHGlobal(dataPtr); - return result; + return bytesRead; } [DllImport(_HIDApiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_read", CharSet = CharSet.Unicode)] diff --git a/Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs b/Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs index d10c38e7..6aa70841 100644 --- a/Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs +++ b/Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs @@ -25,7 +25,7 @@ using VocaluxeLib; namespace Vocaluxe.Lib.Input.WiiMote { - class CWiiMote : IController, IDisposable + class CWiiMote : IController { private CWiiMoteLib _WiiMote; @@ -54,7 +54,7 @@ namespace Vocaluxe.Lib.Input.WiiMote _RumbleTimer = new CRumbleTimer(); _Gesture = new CGesture(); - _HandlerThread = new Thread(_MainLoop) {Priority = ThreadPriority.BelowNormal}; + _HandlerThread = new Thread(_MainLoop) {Name = "WiiMote", Priority = ThreadPriority.BelowNormal}; _KeysPool = new List(); _CurrentKeysPool = new List(); @@ -151,8 +151,7 @@ namespace Vocaluxe.Lib.Input.WiiMote if (startRumble) _WiiMote.SetRumble(true); - - if (stopRumble) + else if (stopRumble) _WiiMote.SetRumble(false); } } @@ -314,15 +313,5 @@ namespace Vocaluxe.Lib.Input.WiiMote _MousePool.Clear(); } } - - public void Dispose() - { - if (_WiiMote != null) - { - _WiiMote.Dispose(); - _WiiMote = null; - } - GC.SuppressFinalize(this); - } } } \ No newline at end of file diff --git a/Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs b/Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs index 7b1449d5..d25097d9 100644 --- a/Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs +++ b/Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs @@ -137,7 +137,7 @@ namespace Vocaluxe.Lib.Input.WiiMote } #endregion Events - public sealed class CWiiMoteLib : IDisposable + public sealed class CWiiMoteLib { // ReSharper disable InconsistentNaming private const ushort _VID = 0x057e; @@ -178,8 +178,7 @@ namespace Vocaluxe.Lib.Input.WiiMote private int _Address; private short _Size; - private readonly Thread _Reader; - private bool _Active; + private Thread _Reader; private readonly bool _Error; public bool Connected { get; private set; } @@ -191,72 +190,63 @@ namespace Vocaluxe.Lib.Input.WiiMote #region Interface public CWiiMoteLib() { - Connected = false; - _Active = true; - _Error = false; - _Reader = new Thread(_ReaderLoop); - _Reader.Start(); - if (!CHIDApi.Init()) { CLog.LogError("WiiMoteLib: Can't initialize HID API"); - const string msg = "Please install the Visual C++ Redistributable Packages 2008!"; - CLog.LogError(msg); + CLog.LogError("Please install the Visual C++ Redistributable Packages 2008!"); - _Active = false; _Error = true; } } ~CWiiMoteLib() { - Dispose(false); + Disconnect(); + //Wait for thread to finish (if any) + _WaitForReader(); + CHIDApi.Exit(); + _ReadDone.Dispose(); } - private bool _TryConnect(ushort pid) + private void _StartReader() { - bool connected = CHIDApi.Open(_VID, pid, out _Handle); - if (connected) + _Reader = new Thread(_ReaderLoop) {Name = "WiiMoteLib"}; + _Reader.Start(); + } + + private void _WaitForReader() + { + if (_Reader == null) + return; + _Reader.Join(); + _Reader = null; + } + + private void _TryConnect(ushort pid) + { + //We might have had a reader thread, that is not finished yet, so let it finish and close it's handle first or it will close the new one + _WaitForReader(); + Connected = CHIDApi.Open(_VID, pid, out _Handle); + if (Connected) { - connected = _ReadCalibration(); - if (!connected) - CHIDApi.Close(_Handle); + _StartReader(); + if (!_ReadCalibration()) + Connected = false; } - return connected; } public bool Connect() { - Connected = false; + if (Connected) + return true; if (_Error) return false; - //Try WiiMotion - Connected = CHIDApi.Open(_VID, _PID, out _Handle); - if (Connected) - { - Connected = _ReadCalibration(); - if (!Connected) - CHIDApi.Close(_Handle); - } - else - CHIDApi.Close(_Handle); - - if (Connected) - return true; - - //Try WiiMotion Plus - Connected = CHIDApi.Open(_VID, _PIDPlus, out _Handle); - if (Connected) - { - Connected = _ReadCalibration(); - if (!Connected) - CHIDApi.Close(_Handle); - } - else - CHIDApi.Close(_Handle); + _TryConnect(_PID); //Try WiiMotion + if (!Connected) + _TryConnect(_PIDPlus); //Try WiiMotion Plus return Connected; } @@ -264,8 +254,6 @@ namespace Vocaluxe.Lib.Input.WiiMote public void Disconnect() { Connected = false; - _Active = false; - CHIDApi.Exit(); } public void SetReportType(EInputReport type, EIRSensitivity irSensitivity, bool continuous) @@ -328,68 +316,54 @@ namespace Vocaluxe.Lib.Input.WiiMote #region Private stuff private void _ReaderLoop() { - while (_Active) + var buff = new byte[_ReportLength]; + while (Connected) { - Thread.Sleep(5); - - if (_Handle != IntPtr.Zero && Connected) + int bytesRead; + try { - var buff = new byte[_ReportLength]; - - try + bytesRead = CHIDApi.ReadTimeout(_Handle, ref buff, _ReportLength, 400); + if (bytesRead == -1) { - CHIDApi.ReadTimeout(_Handle, ref buff, _ReportLength, 200); - } - catch (Exception e) - { - CLog.LogError("(WiiMoteLib) Error reading from device: " + e); - } - - if (_ParseInputReport(buff)) - { - if (WiiMoteChanged != null) - WiiMoteChanged(this, new CWiiMoteChangedEventArgs(_WiiMoteState)); + Connected = false; //Disconnected + break; } } + catch (Exception e) + { + CLog.LogError("(WiiMoteLib) Error reading from device: " + e); + Connected = false; + break; + } + + if (bytesRead > 0 && _ParseInputReport(buff)) + { + if (WiiMoteChanged != null) + WiiMoteChanged(this, new CWiiMoteChangedEventArgs(_WiiMoteState)); + } + Thread.Sleep(5); } + CHIDApi.Close(_Handle); } private bool _ParseInputReport(byte[] buff) { - if (buff == null) - { - Connected = false; - return false; - } - var type = (EInputReport)buff[0]; switch (type) { case EInputReport.Buttons: - _ParseButtons(buff); - break; - - case EInputReport.ButtonsAccel: - _ParseButtons(buff); - _ParseAccel(buff); - break; - - case EInputReport.IRAccel: - _ParseButtons(buff); - _ParseAccel(buff); - _ParseIR(buff); - break; - case EInputReport.ButtonsExtension: _ParseButtons(buff); break; + case EInputReport.ButtonsAccel: case EInputReport.ExtensionAccel: _ParseButtons(buff); _ParseAccel(buff); break; + case EInputReport.IRAccel: case EInputReport.IRExtensionAccel: _ParseButtons(buff); _ParseAccel(buff); @@ -693,24 +667,5 @@ namespace Vocaluxe.Lib.Input.WiiMote Thread.Sleep(100); } #endregion Private stuff - - #region IDisposable Members - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - // ReSharper disable InconsistentNaming - private void Dispose(bool disposing) - // ReSharper restore InconsistentNaming - { - if (disposing) - { - Disconnect(); - _ReadDone.Close(); - } - } - #endregion } } \ No newline at end of file From 76f491b347e141ad784afdf1001d725ad684f5d1 Mon Sep 17 00:00:00 2001 From: Flamefire Date: Tue, 11 Mar 2014 22:38:47 +0100 Subject: [PATCH 16/18] Formatting --- .../ClientServerLib/ICWebservice.cs | 28 ------------------- Vocaluxe/Lib/Sound/CDirectSoundRecord.cs | 2 +- 2 files changed, 1 insertion(+), 29 deletions(-) diff --git a/ClientServerLib/ClientServerLib/ICWebservice.cs b/ClientServerLib/ClientServerLib/ICWebservice.cs index 38f1d5d0..0305e418 100644 --- a/ClientServerLib/ClientServerLib/ICWebservice.cs +++ b/ClientServerLib/ClientServerLib/ICWebservice.cs @@ -28,32 +28,27 @@ namespace ServerLib [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/sendKeyEvent?key={key}")] - void SendKeyEvent(string key); #region profile [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getOwnProfileId")] - int GetOwnProfileId(); [OperationContract, WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/sendProfile")] - void SendProfile(SProfileData profile); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getProfile?profileId={profileId}")] - SProfileData GetProfile(int profileId); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getProfileList")] - SProfileData[] GetProfileList(); #endregion @@ -62,7 +57,6 @@ namespace ServerLib RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/sendPhoto")] - void SendPhoto(SPhotoData photo); #endregion @@ -70,55 +64,46 @@ namespace ServerLib [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/login?username={username}&password={password}")] - Guid Login(string username, string password); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "")] - Stream Index(); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/js/{filename}")] - Stream GetJsFile(String filename); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/css/{filename}")] - Stream GetCssFile(String filename); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/css/images/{filename}")] - Stream GetCssImageFile(String filename); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/img/{filename}")] - Stream GetImgFile(String filename); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/locales/{filename}")] - Stream GetLocaleFile(String filename); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/delayedImage?id={id}")] - CBase64Image GetDelayedImage(String id); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/isServerOnline")] - bool IsServerOnline(); #endregion @@ -126,19 +111,16 @@ namespace ServerLib [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getSong?songId={songId}")] - SSongInfo GetSong(int songId); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getCurrentSongId")] - int GetCurrentSongId(); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getAllSongs")] - SSongInfo[] GetAllSongs(); #endregion @@ -146,43 +128,36 @@ namespace ServerLib [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getPlaylists")] - SPlaylistInfo[] GetPlaylists(); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getPlaylist?id={playlistId}")] - SPlaylistInfo GetPlaylist(int playlistId); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/addSongToPlaylist?songId={songId}&playlistId={playlistId}&duplicates={allowDuplicates}")] - void AddSongToPlaylist(int songId, int playlistId, bool allowDuplicates); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/removeSongFromPlaylist?position={position}&playlistId={playlistId}&songId={songId}")] - void RemoveSongFromPlaylist(int position, int playlistId, int songId); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/moveSongInPlaylist?newPosition={newPosition}&playlistId={playlistId}&songId={songId}")] - void MoveSongInPlaylist(int newPosition, int playlistId, int songId); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/playlistContainsSong?songId={songId}&playlistId={playlistId}")] - bool PlaylistContainsSong(int songId, int playlistId); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getPlaylistSongs?playlistId={playlistId}")] - SPlaylistSongInfo[] GetPlaylistSongs(int playlistId); [OperationContract, WebInvoke(Method = "GET", @@ -200,19 +175,16 @@ namespace ServerLib [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getUserRole?profileId={profileId}")] - int GetUserRole(int profileId); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/setUserRole?profileId={profileId}&userRole={userRole}")] - void SetUserRole(int profileId, int userRole); [OperationContract, WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/hasUserRight?right={right}")] - bool HasUserRight(int right); #endregion } diff --git a/Vocaluxe/Lib/Sound/CDirectSoundRecord.cs b/Vocaluxe/Lib/Sound/CDirectSoundRecord.cs index a769fb5e..4235f8ac 100644 --- a/Vocaluxe/Lib/Sound/CDirectSoundRecord.cs +++ b/Vocaluxe/Lib/Sound/CDirectSoundRecord.cs @@ -326,7 +326,7 @@ namespace Vocaluxe.Lib.Sound for (int i = 0; i < _Notifications.Count; i++) _WaitHandles[i] = _Notifications[i].Event; - _CaptureThread = new Thread(_DoCapture) {Name="DirectSoundCapture",IsBackground = true}; + _CaptureThread = new Thread(_DoCapture) {Name = "DirectSoundCapture", IsBackground = true}; _Running = true; _CaptureThread.Start(); From 424cb826eda50334db524754a36e9b142c9e8ecf Mon Sep 17 00:00:00 2001 From: Flamefire Date: Tue, 11 Mar 2014 22:54:24 +0100 Subject: [PATCH 17/18] Fix crash if there are no songs in highscore --- Vocaluxe/Screens/CScreenHighscore.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Vocaluxe/Screens/CScreenHighscore.cs b/Vocaluxe/Screens/CScreenHighscore.cs index 411cd2cd..01848911 100644 --- a/Vocaluxe/Screens/CScreenHighscore.cs +++ b/Vocaluxe/Screens/CScreenHighscore.cs @@ -279,8 +279,13 @@ namespace Vocaluxe.Screens private void _ChangePos(int num) { - _Pos += num; - _Pos = _Pos.Clamp(0, _Scores[_Round].Count - 1); + if (_Scores[_Round].Count == 0) + _Pos = 0; + else + { + _Pos += num; + _Pos = _Pos.Clamp(0, _Scores[_Round].Count - 1); + } } private void _ChangeRound(int num) From 898819fcf5c9710e221457efa492d6770a757d16 Mon Sep 17 00:00:00 2001 From: Flamefire Date: Wed, 12 Mar 2014 09:41:34 +0100 Subject: [PATCH 18/18] Fix code issues (naming, unused stuff) --- Vocaluxe/Base/CConfig.cs | 8 +- Vocaluxe/Base/CGame.cs | 23 +++--- Vocaluxe/Base/CGraphics.cs | 3 - Vocaluxe/Base/CSettings.cs | 2 +- Vocaluxe/Base/CSongs.cs | 4 +- Vocaluxe/Base/CTheme.cs | 1 - Vocaluxe/Base/Server/CCommands.cs | 3 +- Vocaluxe/Base/Server/CVocaluxeServer.cs | 15 ++-- Vocaluxe/CProgrammHelper.cs | 4 - Vocaluxe/Lib/Playlist/CPlaylistFile.cs | 1 - Vocaluxe/Lib/Sound/CPortAudioPlay.cs | 4 +- Vocaluxe/Screens/CPopupScreenServerQR.cs | 6 -- .../Screens/CScreenOptionsVideoAdjustments.cs | 2 - Vocaluxe/Screens/CScreenScore.cs | 6 +- Vocaluxe/Website/css/style.css | 2 + VocaluxeLib/Enums.cs | 2 + VocaluxeLib/Extensions.cs | 3 +- VocaluxeLib/Menu/CBackground.cs | 9 +-- VocaluxeLib/Menu/CLyric.cs | 2 - VocaluxeLib/Menu/CMenu.cs | 1 - VocaluxeLib/Menu/CMenuPartyNameSelection.cs | 75 ++++++++++++++----- VocaluxeLib/Menu/CNameSelection.cs | 3 +- VocaluxeLib/Menu/SongMenu/CSongMenu.cs | 5 +- .../Menu/SongMenu/CSongMenuTileBoard.cs | 41 +++++----- VocaluxeLib/Profile/CAvatar.cs | 2 +- VocaluxeLib/Profile/CProfile.cs | 11 +-- VocaluxeLib/Songs/CLineBase.cs | 3 +- VocaluxeLib/Songs/CSong.cs | 2 +- VocaluxeLib/Songs/CSungNote.cs | 1 + VocaluxeLib/Songs/CVoice.cs | 4 +- WebserverInitalConfig/CConfigHttpApi.cs | 15 +--- WebserverInitalConfig/HttpApi.cs | 3 - WebserverInitalConfig/Program.cs | 2 - .../Properties/AssemblyInfo.cs | 1 - 34 files changed, 128 insertions(+), 141 deletions(-) diff --git a/Vocaluxe/Base/CConfig.cs b/Vocaluxe/Base/CConfig.cs index c5024d1e..2b5d8b3d 100644 --- a/Vocaluxe/Base/CConfig.cs +++ b/Vocaluxe/Base/CConfig.cs @@ -60,10 +60,10 @@ namespace Vocaluxe.Base public static int ScreenW = 1024; public static int ScreenH = 576; - public static int BorderLeft = 0; - public static int BorderRight = 0; - public static int BorderTop = 0; - public static int BorderBottom = 0; + public static int BorderLeft; + public static int BorderRight; + public static int BorderTop; + public static int BorderBottom; public static EAntiAliasingModes AAMode = EAntiAliasingModes.X0; diff --git a/Vocaluxe/Base/CGame.cs b/Vocaluxe/Base/CGame.cs index 238e314b..009e585f 100644 --- a/Vocaluxe/Base/CGame.cs +++ b/Vocaluxe/Base/CGame.cs @@ -208,7 +208,7 @@ namespace Vocaluxe.Base public static void UpdatePoints(float time) { - bool DEBUG_HIT = false; + const bool DEBUG_HIT = false; CSong song = _SongQueue.GetSong(); @@ -274,8 +274,6 @@ namespace Vocaluxe.Base { int tone = notes[note].Tone; int tonePlayer = CSound.RecordGetTone(p); - if (DEBUG_HIT) - tonePlayer = tone; while (tonePlayer - tone > 6) tonePlayer -= 12; @@ -362,7 +360,7 @@ namespace Vocaluxe.Base public static void ResetToLastLine(int soundStream, int vidStream) { - float[] time = GetLastSungLineStart(); + float[] time = _GetLastSungLineStart(); ResetToTime(time[0], time[1], soundStream, vidStream); } @@ -416,15 +414,15 @@ namespace Vocaluxe.Base CVideo.Skip(vidStream, time, GetSong().VideoGap); } - private static float[] GetLastSungLineStart() + private static float[] _GetLastSungLineStart() { - return GetNoteTimeBeforeBeat(CurrentBeat); + return _GetNoteTimeBeforeBeat(CurrentBeat); } - private static float[] GetNoteTimeBeforeBeat(int beat) + private static float[] _GetNoteTimeBeforeBeat(int beat) { CSong song = GetSong(); - int StartBeat = (int)Math.Floor(beat - GetBeatFromTime(CSettings.PauseResetTime, song.BPM, 0f)); + int startBeat = (int)Math.Floor(beat - GetBeatFromTime(CSettings.PauseResetTime, song.BPM, 0f)); int lastStart = 0; int nextStart = 0; foreach (CVoice voice in song.Notes.Voices) @@ -436,16 +434,13 @@ namespace Vocaluxe.Base { foreach (CSongNote note in line.Notes) { - if (note.StartBeat > StartBeat) + if (note.StartBeat > startBeat) { nextStartNote = note.StartBeat; break; } - else - { - voiceStart = note.StartBeat; - lastEnd = note.EndBeat; - } + voiceStart = note.StartBeat; + lastEnd = note.EndBeat; } if (nextStartNote > 0) break; diff --git a/Vocaluxe/Base/CGraphics.cs b/Vocaluxe/Base/CGraphics.cs index 60356193..92a2577b 100644 --- a/Vocaluxe/Base/CGraphics.cs +++ b/Vocaluxe/Base/CGraphics.cs @@ -404,9 +404,6 @@ namespace Vocaluxe.Base CConfig.BorderTop = 0; CConfig.BorderBottom = 0; break; - - default: - break; } CConfig.SaveConfig(); break; diff --git a/Vocaluxe/Base/CSettings.cs b/Vocaluxe/Base/CSettings.cs index e9dd805d..8d0c527b 100644 --- a/Vocaluxe/Base/CSettings.cs +++ b/Vocaluxe/Base/CSettings.cs @@ -104,7 +104,7 @@ namespace Vocaluxe.Base #endif Path.Combine(DataPath, FolderProfiles) }; - public static string FolderPhotos = "Photos"; + public const string FolderPhotos = "Photos"; public const string FolderSongs = "Songs"; public const string FolderSounds = "Sounds"; public const string FolderLanguages = "Languages"; diff --git a/Vocaluxe/Base/CSongs.cs b/Vocaluxe/Base/CSongs.cs index 7aa205c9..14b2100e 100644 --- a/Vocaluxe/Base/CSongs.cs +++ b/Vocaluxe/Base/CSongs.cs @@ -221,9 +221,7 @@ namespace Vocaluxe.Base return; //Calc avarage sing-count - int totalCounts = 0; - foreach (CSong song in VisibleSongs) - totalCounts += song.NumPlayedSession; + int totalCounts = VisibleSongs.Sum(song => song.NumPlayedSession); int averageCount = totalCounts / NumSongsVisible; foreach (CSong song in VisibleSongs) diff --git a/Vocaluxe/Base/CTheme.cs b/Vocaluxe/Base/CTheme.cs index 42b1bf7e..35180bcb 100644 --- a/Vocaluxe/Base/CTheme.cs +++ b/Vocaluxe/Base/CTheme.cs @@ -18,7 +18,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Text; using System.Windows.Forms; using System.Xml; using Vocaluxe.Base.Fonts; diff --git a/Vocaluxe/Base/Server/CCommands.cs b/Vocaluxe/Base/Server/CCommands.cs index be2b0bae..3d8b70d1 100644 --- a/Vocaluxe/Base/Server/CCommands.cs +++ b/Vocaluxe/Base/Server/CCommands.cs @@ -96,9 +96,8 @@ namespace Vocaluxe.Base.Server var stream = new MemoryStream(); stream.Write(cmd, 0, cmd.Length); - byte[] data; string json = JsonConvert.SerializeObject(obj); - data = _Encoder.GetBytes(json); + byte[] data = _Encoder.GetBytes(json); stream.Write(data, 0, data.Length); return stream.ToArray(); } diff --git a/Vocaluxe/Base/Server/CVocaluxeServer.cs b/Vocaluxe/Base/Server/CVocaluxeServer.cs index 03ede100..154dd1db 100644 --- a/Vocaluxe/Base/Server/CVocaluxeServer.cs +++ b/Vocaluxe/Base/Server/CVocaluxeServer.cs @@ -26,7 +26,6 @@ using ServerLib; using Vocaluxe.Lib.Input; using Vocaluxe.Lib.Playlist; using VocaluxeLib; -using VocaluxeLib.Draw; using VocaluxeLib.Menu; using VocaluxeLib.Profile; using VocaluxeLib.Songs; @@ -314,7 +313,7 @@ namespace Vocaluxe.Base.Server #endregion #region photo - private static List photosOfThisRound = new List(); + private static readonly List _PhotosOfThisRound = new List(); private static bool _SendPhoto(SPhotoData photoData) { @@ -325,17 +324,17 @@ namespace Vocaluxe.Base.Server string filePath = _SaveImage(photoData.Photo, name, CSettings.FolderPhotos); if (!string.IsNullOrEmpty(filePath)) { - photosOfThisRound.Add(filePath); + _PhotosOfThisRound.Add(filePath); return true; } return false; } - internal static string[] getPhotosOfThisRound() + internal static string[] GetPhotosOfThisRound() { - string[] result = photosOfThisRound.ToArray(); - photosOfThisRound.Clear(); + string[] result = _PhotosOfThisRound.ToArray(); + _PhotosOfThisRound.Clear(); return result; } #endregion @@ -583,11 +582,11 @@ namespace Vocaluxe.Base.Server return false; } - byte[] salt = profile.PasswordSalt; + //byte[] salt = profile.PasswordSalt; return hashedPassword.SequenceEqual(profile.PasswordHash); } - private static byte[] _GetPassowordSalt(int profileId) + private static byte[] _GetPasswordSalt(int profileId) { CProfile profile = CProfiles.GetProfile(profileId); if (profile == null) diff --git a/Vocaluxe/CProgrammHelper.cs b/Vocaluxe/CProgrammHelper.cs index 12cf6753..f4425776 100644 --- a/Vocaluxe/CProgrammHelper.cs +++ b/Vocaluxe/CProgrammHelper.cs @@ -16,12 +16,8 @@ #endregion using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Runtime.Serialization; using System.Security; -using System.Text; using Microsoft.Win32; using Vocaluxe.Base; diff --git a/Vocaluxe/Lib/Playlist/CPlaylistFile.cs b/Vocaluxe/Lib/Playlist/CPlaylistFile.cs index 954cc6a7..4ab37b0f 100644 --- a/Vocaluxe/Lib/Playlist/CPlaylistFile.cs +++ b/Vocaluxe/Lib/Playlist/CPlaylistFile.cs @@ -18,7 +18,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Text; using System.Xml; using Vocaluxe.Base; using VocaluxeLib; diff --git a/Vocaluxe/Lib/Sound/CPortAudioPlay.cs b/Vocaluxe/Lib/Sound/CPortAudioPlay.cs index 985d936e..82af2e91 100644 --- a/Vocaluxe/Lib/Sound/CPortAudioPlay.cs +++ b/Vocaluxe/Lib/Sound/CPortAudioPlay.cs @@ -665,7 +665,7 @@ namespace Vocaluxe.Lib.Sound return -1; } - public bool Skip(float time) + public void Skip(float time) { lock (_LockSyncSignals) { @@ -673,8 +673,6 @@ namespace Vocaluxe.Lib.Sound _SetSkip = true; _Waiting = true; } - - return true; } #region Threading diff --git a/Vocaluxe/Screens/CPopupScreenServerQR.cs b/Vocaluxe/Screens/CPopupScreenServerQR.cs index 94ad9f74..a961edd9 100644 --- a/Vocaluxe/Screens/CPopupScreenServerQR.cs +++ b/Vocaluxe/Screens/CPopupScreenServerQR.cs @@ -15,7 +15,6 @@ // along with Vocaluxe. If not, see . #endregion -using ServerLib; using Vocaluxe.Base; using Vocaluxe.Base.Server; using VocaluxeLib; @@ -56,11 +55,6 @@ namespace Vocaluxe.Screens _ThemeTexts = new string[] {_TextServerAddress, _TextServerNotRunning}; } - public override void LoadTheme(string xmlPath) - { - base.LoadTheme(xmlPath); - } - public override void OnShow() { base.OnShow(); diff --git a/Vocaluxe/Screens/CScreenOptionsVideoAdjustments.cs b/Vocaluxe/Screens/CScreenOptionsVideoAdjustments.cs index 774ef686..6c22392b 100644 --- a/Vocaluxe/Screens/CScreenOptionsVideoAdjustments.cs +++ b/Vocaluxe/Screens/CScreenOptionsVideoAdjustments.cs @@ -15,12 +15,10 @@ // along with Vocaluxe. If not, see . #endregion -using System; using System.Windows.Forms; using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Menu; -using VocaluxeLib.Draw; namespace Vocaluxe.Screens { diff --git a/Vocaluxe/Screens/CScreenScore.cs b/Vocaluxe/Screens/CScreenScore.cs index ad079389..db70f56e 100644 --- a/Vocaluxe/Screens/CScreenScore.cs +++ b/Vocaluxe/Screens/CScreenScore.cs @@ -187,8 +187,8 @@ namespace Vocaluxe.Screens if (_SlideShowBGAvailable) _SlideShowBG.Draw(); else - base._DrawBG(); - base._DrawFG(); + _DrawBG(); + _DrawFG(); return true; } @@ -428,7 +428,7 @@ namespace Vocaluxe.Screens private bool _UpdateBackground() { - string[] photos = CVocaluxeServer.getPhotosOfThisRound(); + string[] photos = CVocaluxeServer.GetPhotosOfThisRound(); _SlideShowBG.RemoveSlideShowTextures(); foreach (string photo in photos) _SlideShowBG.AddSlideShowTexture(photo); diff --git a/Vocaluxe/Website/css/style.css b/Vocaluxe/Website/css/style.css index 95fde798..585e930c 100644 --- a/Vocaluxe/Website/css/style.css +++ b/Vocaluxe/Website/css/style.css @@ -22,6 +22,7 @@ position: relative; height: 100%; width: 100%; + background-color: #000000; background-color: rgba(0,0,0,0.7); } @@ -30,6 +31,7 @@ height: 100%; top: 0; margin: 0; + background: #000000; background: rgba(0, 0, 0, 0.3); display: none; position: fixed; diff --git a/VocaluxeLib/Enums.cs b/VocaluxeLib/Enums.cs index 8e68a52c..5ac45bd3 100644 --- a/VocaluxeLib/Enums.cs +++ b/VocaluxeLib/Enums.cs @@ -355,6 +355,7 @@ namespace VocaluxeLib [Flags] public enum EUserRole { + // ReSharper disable InconsistentNaming TR_USERROLE_GUEST = 0, TR_USERROLE_NORMAL = 1, TR_USERROLE_ADMIN = 2, @@ -362,5 +363,6 @@ namespace VocaluxeLib TR_USERROLE_ADDSONGSUSER = 8, TR_USERROLE_PLAYLISTEDITOR = 16, TR_USERROLE_PROFILEEDITOR = 32 + // ReSharper restore InconsistentNaming } } \ No newline at end of file diff --git a/VocaluxeLib/Extensions.cs b/VocaluxeLib/Extensions.cs index 8def331c..4cc4fe2e 100644 --- a/VocaluxeLib/Extensions.cs +++ b/VocaluxeLib/Extensions.cs @@ -19,11 +19,10 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Text; namespace VocaluxeLib { - public static class Extensions + public static class CExtensions { /// /// Resizes the given list to the given size. Removes elements or adds default values diff --git a/VocaluxeLib/Menu/CBackground.cs b/VocaluxeLib/Menu/CBackground.cs index b63de885..7138d3f3 100644 --- a/VocaluxeLib/Menu/CBackground.cs +++ b/VocaluxeLib/Menu/CBackground.cs @@ -54,8 +54,8 @@ namespace VocaluxeLib.Menu private bool _ThemeLoaded; private int _SlideShowCurrent; - private Stopwatch _SlideShowTimer = new Stopwatch(); - private List _SlideShowTextures = new List(); + private readonly Stopwatch _SlideShowTimer = new Stopwatch(); + private readonly List _SlideShowTextures = new List(); public SColorF Color; @@ -69,8 +69,7 @@ namespace VocaluxeLib.Menu { _PartyModeID = partyModeID; _ThemeLoaded = false; - _Theme = new SThemeBackground(); - _Theme.SlideShowTextures = new List(); + _Theme = new SThemeBackground {SlideShowTextures = new List()}; Color = new SColorF(0f, 0f, 0f, 1f); } @@ -102,11 +101,11 @@ namespace VocaluxeLib.Menu _ThemeLoaded &= success; } - string slideShow = ""; int i = 1; while (xmlReader.ItemExists(item + "/SlideShow" + i)) { + string slideShow; xmlReader.GetValue(item + "/SlideShow" + i, out slideShow, String.Empty); if (slideShow != "") _Theme.SlideShowTextures.Add(slideShow); diff --git a/VocaluxeLib/Menu/CLyric.cs b/VocaluxeLib/Menu/CLyric.cs index f4315702..a1c72daa 100644 --- a/VocaluxeLib/Menu/CLyric.cs +++ b/VocaluxeLib/Menu/CLyric.cs @@ -16,8 +16,6 @@ #endregion using System; -using System.Collections.Generic; -using System.Drawing; using System.Xml; using VocaluxeLib.Songs; diff --git a/VocaluxeLib/Menu/CMenu.cs b/VocaluxeLib/Menu/CMenu.cs index 73e53958..c64c9400 100644 --- a/VocaluxeLib/Menu/CMenu.cs +++ b/VocaluxeLib/Menu/CMenu.cs @@ -19,7 +19,6 @@ using System; using System.Collections.Generic; using System.Drawing; using System.IO; -using System.Text; using System.Windows.Forms; using System.Xml; using VocaluxeLib.Draw; diff --git a/VocaluxeLib/Menu/CMenuPartyNameSelection.cs b/VocaluxeLib/Menu/CMenuPartyNameSelection.cs index 1b8686a4..76015829 100644 --- a/VocaluxeLib/Menu/CMenuPartyNameSelection.cs +++ b/VocaluxeLib/Menu/CMenuPartyNameSelection.cs @@ -15,11 +15,8 @@ // along with Vocaluxe. If not, see . #endregion -using System; using System.Collections.Generic; -using System.Linq; using System.Windows.Forms; -using VocaluxeLib.PartyModes; using VocaluxeLib.Draw; using VocaluxeLib.Profile; @@ -94,10 +91,7 @@ namespace VocaluxeLib.Menu _NumPlayer = numPlayer; _NumPlayerTeams = numPlayerTeams; - if (_NumTeams > 0) - _TeamList = new List[_NumTeams]; - else - _TeamList = new List[1]; + _TeamList = new List[_NumTeams > 0 ? _NumTeams : 1]; if (_NumTeams != _NumPlayerTeams.Length) _NumPlayerTeams = new int[_NumTeams]; @@ -126,7 +120,7 @@ namespace VocaluxeLib.Menu { //Handle left/right/up/down _NameSelections[_NameSelection].HandleInput(keyEvent); - int numberPressed = -1; + int numPressed = -1; bool resetSelection = false; switch (keyEvent.Key) { @@ -157,20 +151,65 @@ namespace VocaluxeLib.Menu case Keys.Back: resetSelection = true; break; + + case Keys.D1: + case Keys.NumPad1: + numPressed = 1; + break; + + case Keys.D2: + case Keys.NumPad2: + numPressed = 2; + break; + + case Keys.D3: + case Keys.NumPad3: + numPressed = 3; + break; + + case Keys.D4: + case Keys.NumPad4: + numPressed = 4; + break; + + case Keys.D5: + case Keys.NumPad5: + numPressed = 5; + break; + + case Keys.D6: + case Keys.NumPad6: + numPressed = 6; + break; + + case Keys.D7: + case Keys.NumPad7: + numPressed = 7; + break; + + case Keys.D8: + case Keys.NumPad8: + numPressed = 8; + break; + + case Keys.D9: + case Keys.NumPad9: + numPressed = 9; + break; } - if (numberPressed > 0 || resetSelection) + if (numPressed > 0 || resetSelection) { - if (numberPressed == _SelectingFastPlayerNr || resetSelection) + if (numPressed == _SelectingFastPlayerNr || resetSelection) { //Reset all values _SelectingFastPlayerNr = 0; _SelectingKeyboardActive = false; _NameSelections[_NameSelection].FastSelection(false, -1); } - else if (numberPressed <= _NumPlayerTeams[_CurrentTeam]) + else if (numPressed <= _NumPlayerTeams[_CurrentTeam]) { - _SelectingFastPlayerNr = numberPressed; - _NameSelections[_NameSelection].FastSelection(true, numberPressed); + _SelectingFastPlayerNr = numPressed; + _NameSelections[_NameSelection].FastSelection(true, numPressed); } _SelectingFast = false; } @@ -530,9 +569,7 @@ namespace VocaluxeLib.Menu public SPartyNameOptions GetData() { - SPartyNameOptions option = new SPartyNameOptions(); - option.NumPlayerTeams = _NumPlayerTeams; - option.TeamList = _TeamList; + SPartyNameOptions option = new SPartyNameOptions {NumPlayerTeams = _NumPlayerTeams, TeamList = _TeamList}; return option; } @@ -692,7 +729,7 @@ namespace VocaluxeLib.Menu { if (_NumPlayerTeams[team] == _TeamList[team].Count && !_ChangePlayerNumDynamic) return; - else if (_NumPlayerTeams[team] == _PartyMode.GetMaxPlayerPerTeam()) + if (_NumPlayerTeams[team] == _PartyMode.GetMaxPlayerPerTeam()) return; _NameSelections[_NameSelection].UseProfile(profileID); @@ -707,8 +744,8 @@ namespace VocaluxeLib.Menu { List ids = new List(); ids.AddRange(_TeamList[t]); - for (int p = 0; p < ids.Count; p++) - _RemovePlayer(t, ids[p]); + foreach (int id in ids) + _RemovePlayer(t, id); } } diff --git a/VocaluxeLib/Menu/CNameSelection.cs b/VocaluxeLib/Menu/CNameSelection.cs index 301c2d04..3fd10b95 100644 --- a/VocaluxeLib/Menu/CNameSelection.cs +++ b/VocaluxeLib/Menu/CNameSelection.cs @@ -94,7 +94,7 @@ namespace VocaluxeLib.Menu private int _Player = -1; private readonly List _VisibleProfiles; - private List _UsedProfiles; + private readonly List _UsedProfiles; private CStatic _PlayerSelector; @@ -416,7 +416,6 @@ namespace VocaluxeLib.Menu _Tiles[i].Avatar.Texture = CBase.Profiles.GetAvatar(_VisibleProfiles[i + offset * _Tiles.Count]); _Tiles[i].Avatar.Color = new SColorF(1, 1, 1, 1); _Tiles[i].Name.Text = CBase.Profiles.GetPlayerName(_VisibleProfiles[i + offset * _Tiles.Count]); - ; _Tiles[i].ProfileID = _VisibleProfiles[i + offset * _Tiles.Count]; } else diff --git a/VocaluxeLib/Menu/SongMenu/CSongMenu.cs b/VocaluxeLib/Menu/SongMenu/CSongMenu.cs index 7d5e75fa..964a2ab5 100644 --- a/VocaluxeLib/Menu/SongMenu/CSongMenu.cs +++ b/VocaluxeLib/Menu/SongMenu/CSongMenu.cs @@ -214,7 +214,8 @@ namespace VocaluxeLib.Menu.SongMenu if (_SongMenu != null) _SongMenu.OnHide(); - switch (CBase.Config.GetSongMenuType()) + _Type = CBase.Config.GetSongMenuType(); + switch (_Type) { //case ESongMenu.TR_CONFIG_LIST: // _SongMenu = new CSongMenuList(); @@ -231,8 +232,6 @@ namespace VocaluxeLib.Menu.SongMenu // _SongMenu = new CSongMenuBook(); // break; } - - _Type = CBase.Config.GetSongMenuType(); } } } \ No newline at end of file diff --git a/VocaluxeLib/Menu/SongMenu/CSongMenuTileBoard.cs b/VocaluxeLib/Menu/SongMenu/CSongMenuTileBoard.cs index 2beb4e95..46781018 100644 --- a/VocaluxeLib/Menu/SongMenu/CSongMenuTileBoard.cs +++ b/VocaluxeLib/Menu/SongMenu/CSongMenuTileBoard.cs @@ -67,11 +67,11 @@ namespace VocaluxeLib.Menu.SongMenu { set { - base._PlaySong(value); - base._PreviewIdInternal = value; + _PlaySong(value); + _PreviewIdInternal = value; _UpdatePreview(); } - get { return base._PreviewIdInternal; } + get { return _PreviewIdInternal; } } public override int GetActualSelection() @@ -138,7 +138,7 @@ namespace VocaluxeLib.Menu.SongMenu } if (_Length < 0 && CBase.Sound.GetLength(_PreviewSongStream) > 0 && CBase.Songs.IsInCategory()) - UpdateLength(CBase.Songs.GetVisibleSong(_PreviewId)); + _UpdateLength(CBase.Songs.GetVisibleSong(_PreviewId)); } private void _UpdatePreview() @@ -181,7 +181,7 @@ namespace VocaluxeLib.Menu.SongMenu _MedleyCalcIcon.Visible = song.Medley.Source == EDataSource.Calculated; _MedleyTagIcon.Visible = song.Medley.Source == EDataSource.Tag; - UpdateLength(song); + _UpdateLength(song); } else { @@ -198,23 +198,22 @@ namespace VocaluxeLib.Menu.SongMenu } } - private void UpdateLength(CSong song) + private void _UpdateLength(CSong song) { - if (song != null) - { - float time = CBase.Sound.GetLength(_PreviewSongStream); - if (Math.Abs(song.Finish) > 0.001) - time = song.Finish; + if (song == null) + return; + float time = CBase.Sound.GetLength(_PreviewSongStream); + if (Math.Abs(song.Finish) > 0.001) + time = song.Finish; - // The audiobackend is not yet ready to return the length - if (time > 0) - { - time -= song.Start; - var min = (int)Math.Floor(time / 60f); - var sec = (int)(time - min * 60f); - _SongLength.Text = min.ToString("00") + ":" + sec.ToString("00"); - _Length = time; - } + // The audiobackend is ready to return the length + if (time > 0) + { + time -= song.Start; + var min = (int)Math.Floor(time / 60f); + var sec = (int)(time - min * 60f); + _SongLength.Text = min.ToString("00") + ":" + sec.ToString("00"); + _Length = time; } } @@ -556,7 +555,7 @@ namespace VocaluxeLib.Menu.SongMenu public override void SetSelectedSong(int visibleSongNr) { - base._PlaySong(visibleSongNr); + _PlaySong(visibleSongNr); base.SetSelectedSong(visibleSongNr); if (visibleSongNr >= 0 && visibleSongNr < CBase.Songs.GetNumSongsVisible()) diff --git a/VocaluxeLib/Profile/CAvatar.cs b/VocaluxeLib/Profile/CAvatar.cs index 716884c6..1928c915 100644 --- a/VocaluxeLib/Profile/CAvatar.cs +++ b/VocaluxeLib/Profile/CAvatar.cs @@ -49,7 +49,7 @@ namespace VocaluxeLib.Profile CBase.Drawing.RemoveTexture(ref Texture); } - public string getFileName() + public string GetFileName() { return FileName; } diff --git a/VocaluxeLib/Profile/CProfile.cs b/VocaluxeLib/Profile/CProfile.cs index 7d4e2b54..4e27b4bd 100644 --- a/VocaluxeLib/Profile/CProfile.cs +++ b/VocaluxeLib/Profile/CProfile.cs @@ -17,7 +17,6 @@ using System; using System.IO; -using System.Text; using System.Xml; namespace VocaluxeLib.Profile @@ -71,9 +70,11 @@ namespace VocaluxeLib.Profile FileName = String.Empty; } - public bool LoadProfile() + public bool LoadProfile(string pathName, string fileName) { - return LoadProfile(FilePath, FileName); + FilePath = pathName; + FileName = fileName; + return LoadProfile(); } public bool LoadProfile(string file) @@ -81,10 +82,10 @@ namespace VocaluxeLib.Profile FileName = Path.GetFileName(file); FilePath = Path.GetDirectoryName(file); - return LoadProfile(FilePath, FileName); + return LoadProfile(); } - public bool LoadProfile(string pathName, string fileName) + public bool LoadProfile() { CXMLReader xmlReader = CXMLReader.OpenFile(Path.Combine(FilePath, FileName)); if (xmlReader == null) diff --git a/VocaluxeLib/Songs/CLineBase.cs b/VocaluxeLib/Songs/CLineBase.cs index 2a0bc348..6c972851 100644 --- a/VocaluxeLib/Songs/CLineBase.cs +++ b/VocaluxeLib/Songs/CLineBase.cs @@ -135,11 +135,10 @@ namespace VocaluxeLib.Songs return false; } - public bool IncLastNoteLength() + public void IncLastNoteLength() { if (_Notes.Count > 0) _Notes[NoteCount - 1].Duration++; - return false; } public void DeleteAllNotes() diff --git a/VocaluxeLib/Songs/CSong.cs b/VocaluxeLib/Songs/CSong.cs index e711cd94..c16c1874 100644 --- a/VocaluxeLib/Songs/CSong.cs +++ b/VocaluxeLib/Songs/CSong.cs @@ -97,7 +97,7 @@ namespace VocaluxeLib.Songs public string MP3FileName = String.Empty; public string CoverFileName = String.Empty; - public List BackgroundFileNames = new List(); + public readonly List BackgroundFileNames = new List(); public string VideoFileName = String.Empty; public EAspect VideoAspect = EAspect.Crop; diff --git a/VocaluxeLib/Songs/CSungNote.cs b/VocaluxeLib/Songs/CSungNote.cs index 7dd0e8f7..3fd3b9a1 100644 --- a/VocaluxeLib/Songs/CSungNote.cs +++ b/VocaluxeLib/Songs/CSungNote.cs @@ -41,6 +41,7 @@ namespace VocaluxeLib.Songs /// /// /// + /// public CSungNote(int startBeat, int duration, int tone, CSongNote hitNote, double points) : this(startBeat, duration, tone) { HitNote = hitNote; diff --git a/VocaluxeLib/Songs/CVoice.cs b/VocaluxeLib/Songs/CVoice.cs index 27aaeae0..c9784a3a 100644 --- a/VocaluxeLib/Songs/CVoice.cs +++ b/VocaluxeLib/Songs/CVoice.cs @@ -205,15 +205,13 @@ namespace VocaluxeLib.Songs public void UpdateTimings() { - CSongNote lastNote; - if (_Lines.Count == 0) return; _Lines[0].StartBeat = -10000; for (int i = 1; i < _Lines.Count; i++) { - lastNote = _Lines[i - 1].LastNote; + CSongNote lastNote = _Lines[i - 1].LastNote; CSongNote firstNote = _Lines[i].FirstNote; if ((lastNote != null) && (firstNote != null)) diff --git a/WebserverInitalConfig/CConfigHttpApi.cs b/WebserverInitalConfig/CConfigHttpApi.cs index fe184af4..38002df3 100644 --- a/WebserverInitalConfig/CConfigHttpApi.cs +++ b/WebserverInitalConfig/CConfigHttpApi.cs @@ -15,7 +15,6 @@ // along with Vocaluxe. If not, see . #endregion -using System.Diagnostics; using System.Security.Authentication; using System.Security.Principal; using Security.Cryptography; @@ -166,12 +165,7 @@ namespace WebserverInitalConfig { if (!profile.FirewallEnabled) return true; - foreach (INetFwAuthorizedApplication a in profile.AuthorizedApplications) - { - if (a.ProcessImageFileName == _ExePath) - return true; - } - return false; + return profile.AuthorizedApplications.Cast().Any(a => a.ProcessImageFileName == _ExePath); } private bool _IsPortOpen(INetFwProfile profile) @@ -180,12 +174,7 @@ namespace WebserverInitalConfig if (!profile.FirewallEnabled) return true; - foreach (INetFwOpenPort p in profile.GloballyOpenPorts) - { - if (p.Protocol == protocol && p.Port == _Port) - return true; - } - return false; + return profile.GloballyOpenPorts.Cast().Any(p => p.Protocol == protocol && p.Port == _Port); } private NET_FW_IP_PROTOCOL_ _GetProtocol() diff --git a/WebserverInitalConfig/HttpApi.cs b/WebserverInitalConfig/HttpApi.cs index c248f8b6..39f587ff 100644 --- a/WebserverInitalConfig/HttpApi.cs +++ b/WebserverInitalConfig/HttpApi.cs @@ -18,13 +18,10 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Linq; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; -using System.Text; -using System.Threading.Tasks; namespace WebserverInitalConfig { diff --git a/WebserverInitalConfig/Program.cs b/WebserverInitalConfig/Program.cs index a4f3a315..fc09dac1 100644 --- a/WebserverInitalConfig/Program.cs +++ b/WebserverInitalConfig/Program.cs @@ -19,9 +19,7 @@ using System; using System.Diagnostics; using System.IO; using System.Net; -using System.Net.Mime; using System.Security.Authentication; -using System.Security.Cryptography.X509Certificates; namespace WebserverInitalConfig { diff --git a/WebserverInitalConfig/Properties/AssemblyInfo.cs b/WebserverInitalConfig/Properties/AssemblyInfo.cs index 4665bfa0..4a79c1a6 100644 --- a/WebserverInitalConfig/Properties/AssemblyInfo.cs +++ b/WebserverInitalConfig/Properties/AssemblyInfo.cs @@ -16,7 +16,6 @@ #endregion using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden