Skip to content

Commit

Permalink
Code Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
ilyasbozdemir committed Mar 21, 2024
1 parent b674f22 commit d8b6a10
Show file tree
Hide file tree
Showing 20 changed files with 128 additions and 116 deletions.
6 changes: 3 additions & 3 deletions QuizApp.Console/Configurations/QuizOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ public class QuizOptions
{
public int DurationInMinutes { get; set; } = 45;
public bool IsOpenToPublic { get; set; } = true;
public int NumberOfChoices { get; set; }
public ScoringRules ScoringRules { get; set; }
public List<QuizQuestion> Questions { get; set; }
public int NumberOfChoices { get; set; } = 5;
public ScoringRules ScoringRules { get; set; } = new ScoringRules(0);
public List<QuizQuestion> Questions { get; set; } = new List<QuizQuestion>();
}

7 changes: 5 additions & 2 deletions QuizApp.Console/Constants/AppConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ public class AppConstants
public const string QUESTIONS_LOADED_SUCCESS_MESSAGE = "Sorular başarıyla yüklendi.";
public const string QUIZ_TIME_EXPIRED_MESSAGE = "Quiz süresi doldu. Quiz sonlandırılıyor.";
public const string QUIZ_TIME_NOT_EXPIRED_MESSAGE = "Quiz süresi dolmadı, ancak sonlandırmak istiyor musunuz? (E/H)";
public const string BOOKLET_EXPORT_SUCCESS_MESSAGE_TEMPLATE = "'{0}' kitapçığı başarıyla JSON olarak dışa aktarıldı. Dosya yolu: {1}";
public const string ANSWER_KEYS_EXPORT_SUCCESS_MESSAGE_TEMPLATE = "'{0}' kitapçığının cevap anahtarları başarıyla JSON olarak dışa aktarıldı. Dosya yolu: {1}";

#endregion

Expand Down Expand Up @@ -70,6 +72,8 @@ public class AppConstants
public const string DATA_FETCH_ERROR_MESSAGE_TEMPLATE = "Veriler API'den alınamadı. Hata kodu: {0}";
public const string ERROR_OCCURRED_MESSAGE = "Bir hata oluştu: {0}";
public const string BOOKLET_ID_NOT_FOUND_ERROR_MESSAGE_TEMPLATE = "Hata: Beklenen kitapçık ID bulunamadı. Beklenen ID: {0}";
public const string QUESTIONS_LOAD_FAILED_MESSAGE = "Sorular yüklenirken bir hata oluştu. Kaynakta sorun olabilir veya boş bir yanıt döndü.";
public const string FILE_DESERIALIZE_ERROR_MESSAGE = "Dosya ayrıştırılırken bir hata oluştu. Dosya formatını kontrol edin ve tekrar deneyin.";

#endregion

Expand Down Expand Up @@ -111,8 +115,7 @@ public class AppConstants

public const string QUESTIONS_ARE_BEING_FETCHED_MESSAGE = "Sorular Sunucudan Alınıyor.";
public const string QUESTIONS_FETCHED_SUCCESSFULLY_MESSAGE = "Sorular Sunucudan Başarıyla Alındı";
public const string QUESTIONS_LOAD_FAILED_MESSAGE = "Kaynak sorular yüklenemedi. Lütfen bağlantınızı kontrol edin veya daha sonra tekrar deneyin.";

public const string NETWORK_LOAD_FAILED_MESSAGE = "Kaynak sorular yüklenemedi. Lütfen bağlantınızı kontrol edin veya daha sonra tekrar deneyin.";

#endregion

Expand Down
4 changes: 2 additions & 2 deletions QuizApp.Console/Constants/MenuOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ public static class MenuOptions
{
new MenuOption(
name: string.Format(AppConstants.CREATE_AND_EXPORT_FILE_TITLE_TEMPLATE,AppConstants.JSON_FORMAT_NAME),
action: () => new ExportService().Export(ExportType.Json)
action: () => new ExportService().Export(ExportType.JSON)
),
new MenuOption(
name: string.Format(AppConstants.CREATE_AND_EXPORT_FILE_TITLE_TEMPLATE,AppConstants.XML_FORMAT_NAME),
action: () => new ExportService().Export(ExportType.Xml)
action: () => new ExportService().Export(ExportType.XML)
),
new MenuOption(
name: AppConstants.RETURN_TO_MAIN_MENU,
Expand Down
6 changes: 3 additions & 3 deletions QuizApp.Console/Enums/ExportType.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
namespace QuizAppConsole.Enums;

[Flags]
public enum ExportType
{
Json,
Xml,
Csv
JSON,
XML,
}

11 changes: 3 additions & 8 deletions QuizApp.Console/Models/Data/Booklet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,7 @@

public class Booklet
{
public int Id { get; set; }
public string BookletName { get; set; }
public List<BookletQuestion> Questions { get; set; }

public Booklet()
{
Questions = new List<BookletQuestion>();
}
public int Id { get; set; } = 0;
public string BookletName { get; set; } = "";
public List<BookletQuestion> Questions { get; set; } = new List<BookletQuestion>();
}
10 changes: 5 additions & 5 deletions QuizApp.Console/Models/Data/BookletQuestion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ namespace QuizAppConsole.Models.Data;

public class BookletQuestion
{
public int Id { get; set; }
public string AskText { get; set; }
public string Explanation { get; set; }
public DifficultyLevel Difficulty { get; set; }
public List<BookletQuestionOption> QuestionOptions { get; set; }
public int Id { get; set; } = 0;
public string AskText { get; set; } = "";
public string Explanation { get; set; } = "";
public DifficultyLevel Difficulty { get; set; } = DifficultyLevel.Easy;
public List<BookletQuestionOption> QuestionOptions { get; set; } = new List<BookletQuestionOption>();

public BookletQuestion()
{
Expand Down
6 changes: 3 additions & 3 deletions QuizApp.Console/Models/Data/BookletQuestionOption.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

public class BookletQuestionOption
{
public int Id { get; set; }
public string Text { get; set; }
public bool IsCorrect { get; set; }
public int Id { get; set; } = 0;
public string Text { get; set; } = "";
public bool IsCorrect { get; set; } = false;
}
21 changes: 13 additions & 8 deletions QuizApp.Console/Models/Quiz/Quiz.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,24 @@ namespace QuizAppConsole.Models.Quiz;

public class Quiz
{
public Guid Id { get; set; }
public string Title { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public Guid Id { get; set; } = Guid.NewGuid();
public string Title { get; set; } = "";
public DateTime StartTime { get; set; } = DateTime.Now;
public int DurationInMinutes { get; set; } = 20;
public bool IsActive { get; set; }
public bool IsOpenToPublic { get; set; }
public string Description { get; set; }
public string Creator { get; set; }
public DateTime EndTime { get; set; } = DateTime.Now;

public bool IsActive { get; set; } = false;
public bool IsOpenToPublic { get; set; } = false;
public string Description { get; set; } = "";
public string Creator { get; set; } = "";

public List<QuizQuestion> Questions { get; set; }
public ScoringRules ScoringRules { get; set; }

public Quiz()

Check warning on line 21 in QuizApp.Console/Models/Quiz/Quiz.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'Questions' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

Check warning on line 21 in QuizApp.Console/Models/Quiz/Quiz.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'ScoringRules' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
{

}
public Quiz(Action<QuizOptions> options)

Check warning on line 25 in QuizApp.Console/Models/Quiz/Quiz.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'Questions' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
{
QuizOptions quizOptions = new QuizOptions();
Expand Down
4 changes: 2 additions & 2 deletions QuizApp.Console/Models/Quiz/QuizAnswerOption.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

public class QuizAnswerOption
{
public int Id { get; set; }
public string Text { get; set; }
public int Id { get; set; } = 0;
public string Text { get; set; } = "";
}
8 changes: 4 additions & 4 deletions QuizApp.Console/Models/Quiz/QuizQuestion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

public class QuizQuestion
{
public int Id { get; set; }
public string Text { get; set; }
public List<QuizAnswerOption> AnswerOptions { get; set; } // Sorunun seçenekleri
public int CorrectAnswerId { get; set; } // Doğru cevabın Id'si
public int Id { get; set; } = 0;
public string Text { get; set; } = "";
public List<QuizAnswerOption> AnswerOptions { get; set; } = new List<QuizAnswerOption>(); // Sorunun seçenekleri
public int CorrectAnswerId { get; set; } = 0; // Doğru cevabın Id'si
}
12 changes: 7 additions & 5 deletions QuizApp.Console/Models/User.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

public class User
{
public Guid Id { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<UserQuiz> UserQuizzes { get; set; }
public Guid Id { get; set; }= Guid.NewGuid();
public string Username { get; set; } = "";
public string FirstName { get; set; } = "";
public string LastName { get; set; } = "";
public List<UserQuiz> UserQuizzes { get; set; }= new List<UserQuiz>();

public User() { }

public User(string firstName, string lastName, string username)
{
Expand Down
12 changes: 6 additions & 6 deletions QuizApp.Console/Models/UserQuiz.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
namespace QuizAppConsole.Models;
public class UserQuiz
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public User User { get; set; }
public Guid QuizId { get; set; }
public QuizAppConsole.Models.Quiz.Quiz Quiz { get; set; }
public DateTime StartTime { get; set; }
public Guid Id { get; set; } = Guid.NewGuid();
public Guid UserId { get; set; } = Guid.NewGuid();
public User User { get; set; } = new ();
public Guid QuizId { get; set; } = Guid.NewGuid();
public QuizAppConsole.Models.Quiz.Quiz Quiz { get; set; } = new();
public DateTime StartTime { get; set; } = DateTime.Now;
public DateTime? EndTime { get; set; }
public bool IsCompleted { get; set; } = false;
}
24 changes: 12 additions & 12 deletions QuizApp.Console/Services/ExportService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,31 +9,31 @@ namespace QuizAppConsole.Services;

public class ExportService
{
public static List<BookletViewModel> Booklets { get; private set; }

private AnswerKeyCollection _answerKeys;

public static List<BookletViewModel> Booklets { get; private set; } = new List<BookletViewModel>();
private AnswerKeyCollection _answerKeys { get; set; } = new AnswerKeyCollection();
private const string BaseDirectory = AppConstants.BASE_DIRECTORY;

private QuizService _quizService;

private QuizService _quizService { get; set; } = new QuizService();

public void Export(ExportType exportType)
{
_quizService = new QuizService();

Console.Write(AppConstants.EXPORT_BOOKLET_QUESTION);
int bookletCount = int.Parse(Console.ReadLine());

string input = Console.ReadLine() ?? "";
int bookletCount;
if (!int.TryParse(input, out bookletCount))
bookletCount = 0;

_quizService.GenerateBooklets(bookletCount);
_answerKeys = QuizService.AnswerKeys;
Booklets = QuizService.Booklets;


switch (exportType)
{
case ExportType.Json:
case ExportType.JSON:
ExportEachToJson();
break;
case ExportType.Xml:
case ExportType.XML:
ExportEachToXml();
break;
default:
Expand Down
2 changes: 1 addition & 1 deletion QuizApp.Console/Services/MenuService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ private void HandleSelection()
Console.ForegroundColor = ConsoleColors.Prompt;
Console.Write(AppConstants.CHOOSE_SELECTION_PROMPT);
Console.ForegroundColor = ConsoleColors.Default;
string userInput = Console.ReadLine();
string userInput = Console.ReadLine() ?? "";
int choice;

if (int.TryParse(userInput, out choice))
Expand Down
42 changes: 22 additions & 20 deletions QuizApp.Console/Services/QuestionBuilderService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,43 +6,45 @@
namespace QuizAppConsole.Services;
public class QuestionBuilderService
{
public List<BookletQuestion> LoadQuestionsFromJson(string jsonFilePath = null, string jsonSource = null)
public List<BookletQuestion> LoadQuestionsFromJson(string jsonFilePath = "", string jsonSource = "")
{
try
{
string json = null, fullPath = null;
string json = "", fullPath = "";

if (jsonFilePath != null)
if (jsonFilePath != "")
{
fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, jsonFilePath);
json = File.ReadAllText(fullPath);
}
if (jsonSource != null)
if (jsonSource != "")
json = jsonSource;

if (json == null)
if (json == "")
throw new ArgumentNullException(string.Format(AppConstants.GENERAL_FILE_NOT_SPECIFIED, AppConstants.JSON_FORMAT_NAME));


List<BookletQuestion> questions = JsonConvert.DeserializeObject<List<BookletQuestion>>(json);
List<BookletQuestion> questions = JsonConvert.DeserializeObject<List<BookletQuestion>>(json) ?? new ();

foreach (var question in questions)
if (questions.Count > 0)
{
if (!question.ValidateCorrectOptionCount())
ConsoleHelper.WriteColoredLine(string.Format(AppConstants.INVALID_CORRECT_OPTION_COUNT_TEMPLATE, question.Id), ConsoleColors.Error);

if (!question.ValidateIncorrectOptionCount())
ConsoleHelper.WriteColoredLine(string.Format(AppConstants.INVALID_INCORRECT_OPTION_COUNT_TEMPLATE, question.Id), ConsoleColors.Error);
foreach (var question in questions)
{
if (!question.ValidateCorrectOptionCount())
ConsoleHelper.WriteColoredLine(string.Format(AppConstants.INVALID_CORRECT_OPTION_COUNT_TEMPLATE, question.Id), ConsoleColors.Error);

if (!question.ValidateIncorrectOptionCount())
ConsoleHelper.WriteColoredLine(string.Format(AppConstants.INVALID_INCORRECT_OPTION_COUNT_TEMPLATE, question.Id), ConsoleColors.Error);
}
}



else
ConsoleHelper.WriteColoredLine(AppConstants.NETWORK_LOAD_FAILED_MESSAGE, ConsoleColors.Error);
return questions;
}
catch (JsonReaderException ex)
{

ConsoleHelper.WriteColored(string.Format(AppConstants.FILE_FORMAT_ERROR_MESSAGE_TEMPLATE, ex.Message, AppConstants.JSON_FORMAT_NAME), ConsoleColors.Error);
ConsoleHelper.WriteColored(string.Format(AppConstants.FILE_DESERIALIZE_ERROR_MESSAGE, ex.Message, AppConstants.JSON_FORMAT_NAME), ConsoleColors.Error);
return new List<BookletQuestion>();
}
catch (Exception ex)
Expand All @@ -64,14 +66,14 @@ public async Task<List<BookletQuestion>> LoadQuestionsFromUrl(Uri url)
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();

string contentType = response.Content.Headers.ContentType.MediaType;
string? contentType = response?.Content?.Headers?.ContentType?.MediaType;

if (contentType != AppConstants.APPLICATION_JSON)
throw new InvalidOperationException(string.Format(AppConstants.UNEXPECTED_FILE_CONTENT_MESSAGE_TEMPLATE, AppConstants.JSON_FORMAT_NAME));


if (response.IsSuccessStatusCode)
return LoadQuestionsFromJson(jsonFilePath: null, jsonSource: await response.Content.ReadAsStringAsync());
return LoadQuestionsFromJson(jsonFilePath: "", jsonSource: await response.Content.ReadAsStringAsync());
else
throw new Exception(string.Format(AppConstants.DATA_FETCH_ERROR_MESSAGE_TEMPLATE, response.StatusCode));

Expand All @@ -80,7 +82,7 @@ public async Task<List<BookletQuestion>> LoadQuestionsFromUrl(Uri url)
catch (Exception ex)
{
ConsoleHelper.WriteColoredLine(string.Format(AppConstants.ERROR_OCCURRED_MESSAGE, ex.Message), ConsoleColors.Error);
return new List<BookletQuestion>();
return new();
}
}

Expand Down
4 changes: 2 additions & 2 deletions QuizApp.Console/Services/QuizService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ namespace QuizAppConsole.Services;

public class QuizService
{
public static List<BookletViewModel> Booklets { get; private set; }
public static AnswerKeyCollection AnswerKeys { get; private set; }
public static List<BookletViewModel> Booklets { get; private set; } = new List<BookletViewModel>();
public static AnswerKeyCollection AnswerKeys { get; private set; } = new AnswerKeyCollection();

private List<BookletQuestion> _sourceQuestions;
private readonly QuestionBuilderService _questionLoader;
Expand Down
10 changes: 5 additions & 5 deletions QuizApp.Console/ViewModels/AnswerKeyViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

public class AnswerKeyViewModel
{
public int Id { get; set; }
public int BookletId { get; set; }
public int QuestionId { get; set; }
public int CorrectOptionId { get; set; }
public string CorrectOptionText { get; set; }
public int Id { get; set; } = 0;
public int BookletId { get; set; } = 0;
public int QuestionId { get; set; } = 0;
public int CorrectOptionId { get; set; } = 0;
public string CorrectOptionText { get; set; } = "";
}
8 changes: 4 additions & 4 deletions QuizApp.Console/ViewModels/BookletViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ namespace QuizAppConsole.ViewModels;

public class BookletViewModel
{
public int Id { get; set; }
public string BookletName { get; set; }
public string Prefix { get; set; }
public List<QuestionViewModel> Questions { get; set; }
public int Id { get; set; } = 0;
public string BookletName { get; set; } = "";
public string Prefix { get; set; } = "";
public List<QuestionViewModel> Questions { get; set; } = new List<QuestionViewModel>();
}
6 changes: 3 additions & 3 deletions QuizApp.Console/ViewModels/QuestionOptionViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
namespace QuizAppConsole.ViewModels;
public class QuestionOptionViewModel
{
public int Id { get; set; }
public string Text { get; set; }
public bool IsCorrect { get; set; }
public int Id { get; set; } = 0;
public string Text { get; set; } = "";
public bool IsCorrect { get; set; } = false;
}
Loading

0 comments on commit d8b6a10

Please sign in to comment.