Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions phoneBook.0lcm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Phone Book
This is a learning project made under the requirements set [here](https://thecsharpacademy.com/project/16/phonebook).
This project allows the user to record contacts, including thier name, phone, and email. These contacts are used for basic CRUD operations such as viewing, deleting, or editing a contact.

# Features
* Spectre.Console is used for a cleaner looking console UI.
* After adding a contact, it becomes easy to edit, delete, or view specific details.
* You can easily email your contacts from the app itself, with just the click of a button.
* Besides sending emails, you can also send SMS messages from the app.
* A settings menu is accessible from the main menu, allowing the user to tweak neccesary settings.
* User data such as email settings are stored locally.

# Setup
The application itself just needs to be cloned and run on your machine, however to use emailing and sms features some extra setup is required. In order to use the emailing feature
you'll have to add your email address, as well as your email's app password (not your account password) to the app. This is neccesary step in order to send emails, and is easily
accesible via the settings menu, where you can add or change your login details.
The sms messaging feature does not require any login details, but rather requires a paid API key in order to fully work. In order to get around this the app uses a test key,
meaning no sms messages are actually sent, but rather it's just to show the application's potential. However, if the user wants to use the app for real messaging there are two
options: The user can pay for a [Textbelt](https://textbelt.com) API key and enter it via the settings menu, or they can use the free "textbelt" key which allows for 1 free message
per day.

# Resources Used
[.NET (10.0)](https://learn.microsoft.com/en-us/dotnet/)
[Spectre.Console (0.54.1-alpha.0.68)](https://spectreconsole.net/cli)
[Microsoft.EntityFrameworkCore (10.0.0)](https://learn.microsoft.com/en-us/ef/)
[Microsoft.EntityFrameworkCore.Sqlite (10.0.0)](https://learn.microsoft.com/en-us/ef/core/providers/sqlite/?tabs=dotnet-core-cli)
[Microsoft.Extensions.Hosting (11.0.0-preview.1.26104.118)](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting?view=net-10.0-pp)
[Microsoft.EntityFrameworkCore.Design (10.0.0)](https://learn.microsoft.com/en-us/ef/core/cli/services)
[MailKit (4.15.1)](https://www.mailkit.com)
[MimeKit (4.15.1)](https://mimekit.net)

# Personal Thoughts
This project was suprisingly easier than I thought it would be, which does make me a little nervous that theres something I need to do that I completely missed, but for what I've
done it didn't feel very challenging. Learning how to send an email was probably the most challenging part, but it was pretty fun. Setting up the SMS messaging was pretty simple,
the worst part was that I wanted to find a better API to use to send actual text messages for free, but I ended up settling on just being able to show a test after about an hour
of searching. Overall I thought that the project was pretty easy, or at least easier than I was expecting it to be, and it felt like a smaller project than what I have been doing.
Hopefully I'm not going to have to come back later after saying this to fix some big missing requirement. I'm a little annoyed I couldn't come up with a better option for a free
messaging feature, but I'm at least satisfied with the project, and excited to move on to the next project.
22 changes: 22 additions & 0 deletions phoneBook.0lcm/phoneBook.0lcm.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "phoneBook.0lcm", "phoneBook.0lcm\phoneBook.0lcm.csproj", "{BA25DF73-FCBB-4AB7-ADD1-D1A3CC0A3DE2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "phoneBook.Tests", "phoneBook.Tests\phoneBook.Tests.csproj", "{BAD76563-C171-4A9E-A3A8-FC09D10163C5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BA25DF73-FCBB-4AB7-ADD1-D1A3CC0A3DE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BA25DF73-FCBB-4AB7-ADD1-D1A3CC0A3DE2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BA25DF73-FCBB-4AB7-ADD1-D1A3CC0A3DE2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BA25DF73-FCBB-4AB7-ADD1-D1A3CC0A3DE2}.Release|Any CPU.Build.0 = Release|Any CPU
{BAD76563-C171-4A9E-A3A8-FC09D10163C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BAD76563-C171-4A9E-A3A8-FC09D10163C5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BAD76563-C171-4A9E-A3A8-FC09D10163C5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BAD76563-C171-4A9E-A3A8-FC09D10163C5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
13 changes: 13 additions & 0 deletions phoneBook.0lcm/phoneBook.0lcm/Configuration/AppSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace phoneBook._0lcm.Configuration;

public class AppSettings
{
public string? UserEmail { get; set; }
public string? UserEmailDefault { get; } = null;
public string? UserName { get; set; }
public string? UserNameDefault { get; } = null;
public string? UserAppPassword { get; set; }
public string? UserAppPasswordDefault { get; } = null;
public string TextBeltKey { get; set; } = "textbelt_test";
public string TextBeltKeyDefault { get; } = "textbelt_test";
}
29 changes: 29 additions & 0 deletions phoneBook.0lcm/phoneBook.0lcm/Configuration/SettingsManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System.Text.Json;

namespace phoneBook._0lcm.Configuration;

public class SettingsManager
{
private static readonly string SettingsPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"phoneBook.0lcm",
"settings.json");

public AppSettings Load()
{
if (!File.Exists(SettingsPath))
return new AppSettings();

var json = File.ReadAllText(SettingsPath);
return JsonSerializer.Deserialize<AppSettings>(json) ?? new AppSettings();
}

public void Save(AppSettings settings)
{
var directory = Path.GetDirectoryName(SettingsPath)!;
Directory.CreateDirectory(directory);

var json = JsonSerializer.Serialize(settings, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(SettingsPath, json);
}
}
26 changes: 26 additions & 0 deletions phoneBook.0lcm/phoneBook.0lcm/Data/AppDbContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using phoneBook._0lcm.Models;

namespace phoneBook._0lcm.Data;

public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<ContactClass> ContactClasses { get; set; }
}

public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
var dbPath = Path.Combine(
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Code Duplication

💡 Database path construction is duplicated from Program.cs. Consider sharing this path creation logic.

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"phoneBook.0lcm",
"app.db");

var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
optionsBuilder.UseSqlite($"Data Source={dbPath}");

return new AppDbContext(optionsBuilder.Options);
}
}
18 changes: 18 additions & 0 deletions phoneBook.0lcm/phoneBook.0lcm/Data/DbSeeder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using phoneBook._0lcm.Models;

namespace phoneBook._0lcm.Data;

public class DbSeeder
{
public static async Task SeedContactsAsync(AppDbContext db)
{
var sampleContacts = new List<ContactClass>
{
new() { Name = "John Doe", PhoneNumber = "+1 (312) 555-0175", Email = "John-Doe@gmail.com" },
new() { Name = "Jane Doe", PhoneNumber = "+44 121 496 0329", Email = "Jane_Doe@hotmail.com" }
};

await db.ContactClasses.AddRangeAsync(sampleContacts);
await db.SaveChangesAsync();
}
}
15 changes: 15 additions & 0 deletions phoneBook.0lcm/phoneBook.0lcm/Enums/EnumExtender.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.Text.RegularExpressions;

namespace phoneBook._0lcm.Enums;

internal static class EnumExtender
{
internal static string ToDisplayString(this Enum value)
{
return Regex.Replace(
value.ToString(),
"([a-z])([A-Z])",
"$1 $2"
);
}
}
28 changes: 28 additions & 0 deletions phoneBook.0lcm/phoneBook.0lcm/Enums/Enums.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
namespace phoneBook._0lcm.Enums;

internal enum MainMenuOption
{
AddNewContact,
ViewContacts,
Settings,
Exit
}

internal enum ContactViewingOption
{
EditContact,
DeleteContact,
SendAnEmail,
SendAnSmsMessage,
Back
}

internal enum SettingsMenuOption
{
SetEmailAddress,
SetAppPassword,
SetDisplayName,
SetTextbeltKey,
ResetSettings,
Back
}
73 changes: 73 additions & 0 deletions phoneBook.0lcm/phoneBook.0lcm/Logging/Logging.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Console;

namespace phoneBook._0lcm.Logging;

internal class CustomFormatter : ConsoleFormatter
{
public CustomFormatter() : base("customFormatter")
{
}

public override void Write<TState>(
in LogEntry<TState> logEntry,
IExternalScopeProvider? scopeProvider,
TextWriter textWriter
)
{
var message = logEntry.Formatter(logEntry.State, logEntry.Exception);
if (string.IsNullOrEmpty(message)) return;

var originalColor = Console.ForegroundColor;
try
{
Console.ForegroundColor = GetLogLevelColor(logEntry.LogLevel);

textWriter.Write($"[{DateTimeOffset.Now:HH:mm:ss}]");

textWriter.Write($"[{logEntry.LogLevel,-12}]");

textWriter.Write($"[{logEntry.Category}]");

textWriter.Write(message);

if (logEntry.Exception != null) textWriter.Write(logEntry.Exception.ToString());
}
finally
{
Console.ForegroundColor = originalColor;
}
}

private static ConsoleColor GetLogLevelColor(LogLevel logLevel)
{
return logLevel switch
{
LogLevel.Trace => ConsoleColor.Gray,
LogLevel.Debug => ConsoleColor.Gray,
LogLevel.Information => ConsoleColor.Green,
LogLevel.Warning => ConsoleColor.Yellow,
LogLevel.Error => ConsoleColor.Red,
LogLevel.Critical => ConsoleColor.Magenta,
_ => ConsoleColor.White
};
}
}

internal class AppLogger
{
private static readonly ILoggerFactory AppLoggerFactory =
LoggerFactory.Create(builder =>
{
builder
.SetMinimumLevel(LogLevel.Debug)
.AddConsole(options => { options.FormatterName = "customFormatter"; })
.AddConsoleFormatter<CustomFormatter, ConsoleFormatterOptions>();
});

internal static ILogger CreateLogger<T>()
{
return AppLoggerFactory.CreateLogger<T>();
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace phoneBook._0lcm.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ContactClasses",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(type: "TEXT", nullable: false),
Email = table.Column<string>(type: "TEXT", nullable: false),
PhoneNumber = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ContactClasses", x => x.Id);
});
}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ContactClasses");
}
}
}
Loading