diff --git a/.editorconfig b/.editorconfig
index 7d87f5a..5465255 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -38,17 +38,71 @@ dotnet_diagnostic.CS8524.severity = none
# IDE0044: Add readonly modifier
dotnet_diagnostic.IDE0044.severity = silent
-# IDE0090: Use new(...) syntax
-dotnet_diagnostic.IDE0090.severity = silent
-
# actual nice code formatting rules (Allman style)
[*.cs]
csharp_new_line_before_open_brace = all
indent_size = 4
+csharp_indent_labels = one_less_than_current
+csharp_using_directive_placement = outside_namespace:suggestion
+csharp_prefer_simple_using_statement = true:suggestion
+csharp_prefer_braces = true:silent
+csharp_style_namespace_declarations = file_scoped:warning
+csharp_style_prefer_method_group_conversion = true:silent
+csharp_style_prefer_top_level_statements = true:silent
+csharp_style_prefer_primary_constructors = true:suggestion
+csharp_style_expression_bodied_methods = false:silent
+csharp_style_expression_bodied_constructors = false:silent
+csharp_style_expression_bodied_operators = false:silent
+csharp_style_expression_bodied_properties = true:silent
+csharp_style_expression_bodied_indexers = true:silent
+csharp_style_expression_bodied_accessors = true:silent
+csharp_style_expression_bodied_lambdas = true:silent
+csharp_style_expression_bodied_local_functions = false:silent
+csharp_style_throw_expression = true:suggestion
+csharp_style_prefer_null_check_over_type_check = true:suggestion
+csharp_prefer_simple_default_expression = true:suggestion
+csharp_style_prefer_local_over_anonymous_function = true:suggestion
+csharp_style_prefer_index_operator = true:suggestion
+csharp_style_prefer_range_operator = true:suggestion
+csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
+csharp_style_prefer_tuple_swap = true:suggestion
+csharp_style_prefer_utf8_string_literals = true:suggestion
+csharp_style_inlined_variable_declaration = true:suggestion
# book formatting rules (K&R) to save space
+# SYSLIB1045: Convert to 'GeneratedRegexAttribute'.
+dotnet_diagnostic.SYSLIB1045.severity = silent
+
+# CA1822: Mark members as static
+dotnet_diagnostic.CA1822.severity = silent
+
[*.csxx]
csharp_new_line_before_open_brace = none
indent_size = 2
+
+[*.{cs,vb}]
+dotnet_style_operator_placement_when_wrapping = beginning_of_line
+tab_width = 4
+indent_size = 4
+end_of_line = crlf
+dotnet_style_coalesce_expression = true:suggestion
+dotnet_style_null_propagation = true:suggestion
+dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
+dotnet_style_prefer_auto_properties = true:error
+dotnet_style_object_initializer = true:suggestion
+dotnet_style_prefer_collection_expression = true:suggestion
+dotnet_style_collection_initializer = true:suggestion
+dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
+dotnet_style_prefer_conditional_expression_over_assignment = true:silent
+dotnet_style_prefer_conditional_expression_over_return = true:suggestion
+dotnet_style_explicit_tuple_names = true:suggestion
+dotnet_style_prefer_inferred_tuple_names = true:suggestion
+dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
+dotnet_style_prefer_compound_assignment = true:suggestion
+dotnet_style_prefer_simplified_interpolation = true:suggestion
+dotnet_style_namespace_match_folder = true:suggestion
+
+# IDE0045: Convert to conditional expression
+dotnet_diagnostic.IDE0045.severity = silent
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000..013007b
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,3 @@
+{
+ "dotnet.preferCSharpExtension": true
+}
\ No newline at end of file
diff --git a/CH02/Algorithms/Algorithms.csproj b/CH02/Algorithms/Algorithms.csproj
index dbc1517..61718a1 100644
--- a/CH02/Algorithms/Algorithms.csproj
+++ b/CH02/Algorithms/Algorithms.csproj
@@ -1,7 +1,3 @@
-
- net6.0
-
-
diff --git a/CH02/Algorithms/Structs.cs b/CH02/Algorithms/Structs.cs
index bd22e4c..fca71f5 100644
--- a/CH02/Algorithms/Structs.cs
+++ b/CH02/Algorithms/Structs.cs
@@ -9,7 +9,7 @@ private struct Point
public int X;
public int Y;
- public override string ToString() => $"X:{X},Y:{Y}";
+ public override readonly string? ToString() => $"X:{X},Y:{Y}";
}
public static void Main()
diff --git a/CH02/Arrays/Arrays.cs b/CH02/Arrays/Arrays.cs
index 5621c88..152ef83 100644
--- a/CH02/Arrays/Arrays.cs
+++ b/CH02/Arrays/Arrays.cs
@@ -4,11 +4,13 @@ namespace Arrays;
public class Arrays
{
+ private static readonly int[] values = [1, 2, 3, 4];
+
public static int ArrayVsList()
{
- var a = new int[] { 1, 2, 3, 4 };
+ var a = values;
int sum1 = a[0] + a[1] + a[2] + a[3];
- var b = new List(new int[] { 1, 2, 3, 4 });
+ var b = new List(values);
int sum2 = b[0] + b[1] + b[2] + b[2];
return sum1 + sum2;
}
diff --git a/CH02/Arrays/Arrays.csproj b/CH02/Arrays/Arrays.csproj
index 56293bc..778fafb 100644
--- a/CH02/Arrays/Arrays.csproj
+++ b/CH02/Arrays/Arrays.csproj
@@ -1,6 +1,5 @@
- net6.0
Exe
diff --git a/CH02/HashCode/HashCode.csproj b/CH02/HashCode/HashCode.csproj
index 4b9482e..f60575d 100644
--- a/CH02/HashCode/HashCode.csproj
+++ b/CH02/HashCode/HashCode.csproj
@@ -1,11 +1,10 @@
-
- net6.0
- Library
- false
-
-
-
-
-
+
+ Library
+ false
+
+
+
+
+
\ No newline at end of file
diff --git a/CH02/HashCode/HashCodeTest.cs b/CH02/HashCode/HashCodeTest.cs
index 1a78b3e..a0efcdf 100644
--- a/CH02/HashCode/HashCodeTest.cs
+++ b/CH02/HashCode/HashCodeTest.cs
@@ -2,7 +2,7 @@
{
public int Halue { get; set; }
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
return obj is HashCodeTest test &&
Halue == test.Halue;
diff --git a/CH02/HashCode/ProperGetHashCode.cs b/CH02/HashCode/ProperGetHashCode.cs
index c986ba2..bfda784 100644
--- a/CH02/HashCode/ProperGetHashCode.cs
+++ b/CH02/HashCode/ProperGetHashCode.cs
@@ -6,7 +6,7 @@
public override int GetHashCode()
{
return (int)(((TopicId & 0xFFFF) << 16)
- ^ (TopicId & 0xFFFF0000 >> 16)
+ ^ (TopicId & (0xFFFF0000 >> 16))
^ EntryId);
}
}
\ No newline at end of file
diff --git a/CH02/Nullability/DbId.cs b/CH02/Nullability/DbId.cs
index dbe29c6..e2e023a 100644
--- a/CH02/Nullability/DbId.cs
+++ b/CH02/Nullability/DbId.cs
@@ -6,21 +6,18 @@ public class DbId : IEquatable
public DbId(int id)
{
- if (id <= 0)
- {
- throw new ArgumentOutOfRangeException(nameof(id));
- }
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(id);
Value = id;
}
public override string ToString() => Value.ToString();
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
return Equals(obj as DbId);
}
- public bool Equals(DbId other) => other?.Value == Value;
+ public bool Equals(DbId? other) => other?.Value == Value;
public override int GetHashCode()
{
@@ -38,23 +35,14 @@ public override int GetHashCode()
}
}
-public class EntryId : DbId
+public class EntryId(int id) : DbId(id)
{
- public EntryId(int id) : base(id)
- {
- }
}
-public class TopicId : DbId
+public class TopicId(int id) : DbId(id)
{
- public TopicId(int id) : base(id)
- {
- }
}
-public class UserId : DbId
+public class UserId(int id) : DbId(id)
{
- public UserId(int id) : base(id)
- {
- }
}
\ No newline at end of file
diff --git a/CH02/Nullability/Nullability.csproj b/CH02/Nullability/Nullability.csproj
index 007f9ef..b1b8374 100644
--- a/CH02/Nullability/Nullability.csproj
+++ b/CH02/Nullability/Nullability.csproj
@@ -1,9 +1,5 @@
-
- net6.0
-
-
diff --git a/CH02/Nullability/Person.cs b/CH02/Nullability/Person.cs
index be74d45..53f2953 100644
--- a/CH02/Nullability/Person.cs
+++ b/CH02/Nullability/Person.cs
@@ -15,28 +15,19 @@ internal class ConferenceRegistration
#pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
-internal class ConferenceRegistration2
+internal class ConferenceRegistration2(
+ string firstName,
+ string? middleName,
+ string lastName,
+ string email,
+ string campaignSource = "organic")
{
- public string CampaignSource { get; private set; }
- public string FirstName { get; private set; }
- public string? MiddleName { get; private set; }
- public string LastName { get; private set; }
- public string Email { get; private set; }
- public DateTimeOffset CreatedOn { get; private set; } = DateTime.Now;
-
- public ConferenceRegistration2(
- string firstName,
- string? middleName,
- string lastName,
- string email,
- string? campaignSource = null)
- {
- FirstName = firstName;
- MiddleName = middleName;
- LastName = lastName;
- Email = email;
- CampaignSource = campaignSource ?? "organic";
- }
+ public string CampaignSource { get; } = campaignSource;
+ public string FirstName { get; } = firstName;
+ public string? MiddleName { get; } = middleName;
+ public string LastName { get; } = lastName;
+ public string Email { get; } = email;
+ public DateTimeOffset CreatedOn { get; } = DateTime.Now;
}
internal class ConferenceRegistration3
diff --git a/CH02/Nullability/TopicService.cs b/CH02/Nullability/TopicService.cs
index 137e95e..eb0fbe6 100644
--- a/CH02/Nullability/TopicService.cs
+++ b/CH02/Nullability/TopicService.cs
@@ -12,21 +12,12 @@ public interface IUser
bool Authorized(string role);
}
-public class TopicService
+public class TopicService(IDatabase db, IUser user)
{
- private IDatabase db;
- private IUser user;
-
public MoveResult MoveContents(TopicId from, TopicId to)
{
- if (from is null)
- {
- throw new ArgumentNullException(nameof(from));
- }
- if (to is null)
- {
- throw new ArgumentNullException(nameof(to));
- }
+ ArgumentNullException.ThrowIfNull(from);
+ ArgumentNullException.ThrowIfNull(to);
if (!user.Authorized("move_contents"))
{
return MoveResult.Unauthorized;
diff --git a/CH02/ReferenceVsValueTypes/ReferenceVsValueTypes.csproj b/CH02/ReferenceVsValueTypes/ReferenceVsValueTypes.csproj
index 7495460..6a70a1a 100644
--- a/CH02/ReferenceVsValueTypes/ReferenceVsValueTypes.csproj
+++ b/CH02/ReferenceVsValueTypes/ReferenceVsValueTypes.csproj
@@ -2,7 +2,6 @@
Exe
- net6.0
diff --git a/CH02/Strings/Locales.cs b/CH02/Strings/Locales.cs
index 8ed71f6..27638f7 100644
--- a/CH02/Strings/Locales.cs
+++ b/CH02/Strings/Locales.cs
@@ -1,6 +1,4 @@
using System;
-using System.Collections.Generic;
-using System.Text;
class Locales
{
@@ -8,6 +6,7 @@ public bool isGif(string fileName)
{
return fileName.ToLower().EndsWith(".gif");
}
+
public bool isGifFast(string fileName)
{
return fileName.EndsWith(".gif", StringComparison.OrdinalIgnoreCase);
diff --git a/CH02/Strings/Strings.csproj b/CH02/Strings/Strings.csproj
index fff7812..c632161 100644
--- a/CH02/Strings/Strings.csproj
+++ b/CH02/Strings/Strings.csproj
@@ -1,7 +1,3 @@
-
- net6.0
-
-
diff --git a/CH02/Supercalifragilisticexpialidocious/Program.cs b/CH02/Supercalifragilisticexpialidocious/Program.cs
index 52855f4..58ac075 100644
--- a/CH02/Supercalifragilisticexpialidocious/Program.cs
+++ b/CH02/Supercalifragilisticexpialidocious/Program.cs
@@ -14,7 +14,7 @@ public static void Main()
}
// URL format is https://supercalifragilisticexpialidocious.io/
- public string GetShortCodeStr(string url)
+ public string? GetShortCodeStr(string url)
{
const string urlValidationPattern = @"^https?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$";
if (!Regex.IsMatch(url, urlValidationPattern))
@@ -28,7 +28,7 @@ public string GetShortCodeStr(string url)
}
// URL format is https://supercalifragilisticexpialidocious.io/
- public string GetShortCodeUri(Uri url)
+ public string? GetShortCodeUri(Uri url)
{
string path = url.AbsolutePath;
if (path.Contains('/'))
@@ -38,9 +38,9 @@ public string GetShortCodeUri(Uri url)
return path;
}
- public void IPLoopback()
+ public static void IPLoopback()
{
- var testAddress = IPAddress.Loopback;
+ _ = IPAddress.Loopback;
}
public void BirthDateCalculator()
diff --git a/CH02/Supercalifragilisticexpialidocious/Supercalifragilisticexpialidocious.csproj b/CH02/Supercalifragilisticexpialidocious/Supercalifragilisticexpialidocious.csproj
index 3980c74..7cabd8d 100644
--- a/CH02/Supercalifragilisticexpialidocious/Supercalifragilisticexpialidocious.csproj
+++ b/CH02/Supercalifragilisticexpialidocious/Supercalifragilisticexpialidocious.csproj
@@ -1,12 +1,11 @@
-
- Exe
- net6.0
-
+
+ Exe
+
-
-
-
+
+
+
diff --git a/CH02/ValidationContext/Arrow.cs b/CH02/ValidationContext/Arrow.cs
index 532e771..38238cf 100644
--- a/CH02/ValidationContext/Arrow.cs
+++ b/CH02/ValidationContext/Arrow.cs
@@ -2,10 +2,10 @@
internal class Arrow
{
- public int Sum1(int a, int b)
+ public static int Sum1(int a, int b)
{
return a + b;
}
- public int Sum2(int a, int b) => a + b;
+ public static int Sum2(int a, int b) => a + b;
}
\ No newline at end of file
diff --git a/CH02/ValidationContext/DbId.cs b/CH02/ValidationContext/DbId.cs
index 823e5d9..a3c703a 100644
--- a/CH02/ValidationContext/DbId.cs
+++ b/CH02/ValidationContext/DbId.cs
@@ -6,10 +6,7 @@ public class DbId
public DbId(int id)
{
- if (id <= 0)
- {
- throw new ArgumentOutOfRangeException(nameof(id));
- }
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(id);
Value = id;
}
@@ -17,7 +14,7 @@ public DbId(int id)
public override int GetHashCode() => Value;
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
return obj is DbId other && other.Value == Value;
}
@@ -32,24 +29,15 @@ public override bool Equals(object obj)
return !a.Equals(b);
}
- public class PostId : DbId
+ public class PostId(int id) : DbId(id)
{
- public PostId(int id) : base(id)
- {
- }
}
- public class TopicId : DbId
+ public class TopicId(int id) : DbId(id)
{
- public TopicId(int id) : base(id)
- {
- }
}
- public class UserId : DbId
+ public class UserId(int id) : DbId(id)
{
- public UserId(int id) : base(id)
- {
- }
}
}
\ No newline at end of file
diff --git a/CH02/ValidationContext/ParameterTypes.cs b/CH02/ValidationContext/ParameterTypes.cs
index 623b6c1..c9c9f61 100644
--- a/CH02/ValidationContext/ParameterTypes.cs
+++ b/CH02/ValidationContext/ParameterTypes.cs
@@ -1,34 +1,29 @@
-public struct TopicId
+public struct TopicId(int id)
{
- public int Id { get; private set; }
-
- public TopicId(int id)
- {
- this.Id = id;
- }
+ public int Id { get; private set; } = id;
}
partial class ParameterTypes
{
- public int Move(int from, int to)
+ public static int Move(int from, int to)
{
// ... some cryptic code here
return 0;
}
- public int MoveContents(int fromTopicId, int toTopicId)
+ public static int MoveContents(int fromTopicId, int toTopicId)
{
// ... some cryptic code here
return 0;
}
- public MoveResult MoveContentsB(int fromTopicId, int toTopicId)
+ public static MoveResult MoveContentsB(int fromTopicId, int toTopicId)
{
// ... still quite a code here
return MoveResult.Success;
}
- public MoveResult MoveContentsC(TopicId from, TopicId to)
+ public static MoveResult MoveContentsC(TopicId from, TopicId to)
{
// ... still quite a code here
return MoveResult.Success;
diff --git a/CH02/ValidationContext/PostId.cs b/CH02/ValidationContext/PostId.cs
index 3cb3e3c..0dd453e 100644
--- a/CH02/ValidationContext/PostId.cs
+++ b/CH02/ValidationContext/PostId.cs
@@ -6,10 +6,7 @@ public class PostId : IEquatable
public PostId(int id)
{
- if (id <= 0)
- {
- throw new ArgumentOutOfRangeException(nameof(id));
- }
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(id);
Value = id;
}
@@ -17,12 +14,12 @@ public PostId(int id)
public override int GetHashCode() => Value;
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
return Equals(obj as PostId);
}
- public bool Equals(PostId other) => other?.Value == Value;
+ public bool Equals(PostId? other) => other?.Value == Value;
public static bool operator ==(PostId a, PostId b)
{
diff --git a/CH02/ValidationContext/ValidationContext.csproj b/CH02/ValidationContext/ValidationContext.csproj
index fff7812..c632161 100644
--- a/CH02/ValidationContext/ValidationContext.csproj
+++ b/CH02/ValidationContext/ValidationContext.csproj
@@ -1,7 +1,3 @@
-
- net6.0
-
-
diff --git a/CH03/ClassesVsStructs/ClassesVsStructs.csproj b/CH03/ClassesVsStructs/ClassesVsStructs.csproj
index dbc1517..c96f78e 100644
--- a/CH03/ClassesVsStructs/ClassesVsStructs.csproj
+++ b/CH03/ClassesVsStructs/ClassesVsStructs.csproj
@@ -1,7 +1,11 @@
-
- net6.0
+
+ 9999
+
+
+
+ 9999
diff --git a/CH03/ClassesVsStructs/Identifier.cs b/CH03/ClassesVsStructs/Identifier.cs
index bbfd976..1aca869 100644
--- a/CH03/ClassesVsStructs/Identifier.cs
+++ b/CH03/ClassesVsStructs/Identifier.cs
@@ -2,46 +2,28 @@
namespace Class
{
- public class Id
+ public class Id(int value)
{
- public int Value { get; private set; }
-
- public Id(int value)
- {
- this.Value = value;
- }
+ public int Value { get; private set; } = value;
}
- public class Person
+ public class Person(int id, string firstName, string lastName,
+ string city)
{
- public int Id { get; private set; }
- public string FirstName { get; private set; }
- public string LastName { get; private set; }
- public string City { get; private set; }
-
- public Person(int id, string firstName, string lastName,
- string city)
- {
- Id = id;
- FirstName = firstName;
- LastName = lastName;
- City = city;
- }
+ public int Id { get; private set; } = id;
+ public string FirstName { get; private set; } = firstName;
+ public string LastName { get; private set; } = lastName;
+ public string City { get; private set; } = city;
}
}
namespace Struct
{
- public struct Id
+ public struct Id(int value)
{
- public int Value { get; private set; }
+ public int Value { get; private set; } = value;
- public Id(int value)
- {
- this.Value = value;
- }
-
- private void testMethod()
+ public static void TestMethod()
{
var a = new Person(42, "Sedat", "Kapanoglu", "San Francisco");
var b = a;
@@ -51,20 +33,12 @@ private void testMethod()
}
}
- public struct Person
+ public struct Person(int id, string firstName, string lastName,
+ string city)
{
- public int Id { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string City { get; set; }
-
- public Person(int id, string firstName, string lastName,
- string city)
- {
- Id = id;
- FirstName = firstName;
- LastName = lastName;
- City = city;
- }
+ public int Id { get; set; } = id;
+ public string FirstName { get; set; } = firstName;
+ public string LastName { get; set; } = lastName;
+ public string City { get; set; } = city;
}
}
\ No newline at end of file
diff --git a/CH03/EmojiChat/Controllers/StatsController.cs b/CH03/EmojiChat/Controllers/StatsController.cs
index 8359a5e..0b994d3 100644
--- a/CH03/EmojiChat/Controllers/StatsController.cs
+++ b/CH03/EmojiChat/Controllers/StatsController.cs
@@ -1,6 +1,6 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
-using System.Data.SqlClient;
+using Microsoft.Data.SqlClient;
public class UserStats
{
@@ -9,20 +9,13 @@ public class UserStats
}
[Route("stats/{action}")]
-public class StatsController : ControllerBase
+public class StatsController(IConfiguration config) : ControllerBase
{
- private readonly IConfiguration config;
-
- public StatsController(IConfiguration config)
- {
- this.config = config;
- }
-
[HttpGet]
public UserStats Get(int userId)
{
var result = new UserStats();
- string connectionString = config.GetConnectionString("DB");
+ string connectionString = config.GetConnectionString("DB")!;
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
diff --git a/CH03/EmojiChat/Controllers/WeatherForecastController.cs b/CH03/EmojiChat/Controllers/WeatherForecastController.cs
index 8c2a1ff..b73d2b6 100644
--- a/CH03/EmojiChat/Controllers/WeatherForecastController.cs
+++ b/CH03/EmojiChat/Controllers/WeatherForecastController.cs
@@ -8,29 +8,23 @@ namespace EmojiChat.Controllers;
[ApiController]
[Route("[controller]")]
-public class WeatherForecastController : ControllerBase
+public class WeatherForecastController(ILogger logger) : ControllerBase
{
- private static readonly string[] summaries = new[] {
- "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
-};
-
- private readonly ILogger logger;
-
- public WeatherForecastController(ILogger logger)
- {
- this.logger = logger;
- }
+ private static readonly string[] summaries = [
+ "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm",
+ "Balmy", "Hot", "Sweltering", "Scorching"
+ ];
[HttpGet]
public IEnumerable Get()
{
+ logger.LogDebug("GET request received");
var rng = new Random();
- return Enumerable.Range(1, 5).Select(index => new WeatherForecast
- {
- Date = DateTime.Now.AddDays(index),
- TemperatureC = rng.Next(-20, 55),
- Summary = summaries[rng.Next(summaries.Length)]
- })
- .ToArray();
+ return Enumerable.Range(1, 5)
+ .Select(index => new WeatherForecast(
+ Date: DateTime.Now.AddDays(index),
+ TemperatureC: rng.Next(-20, 55),
+ Summary: summaries[rng.Next(summaries.Length)]))
+ .ToArray();
}
}
\ No newline at end of file
diff --git a/CH03/EmojiChat/EmojiChat.csproj b/CH03/EmojiChat/EmojiChat.csproj
index dc87473..7fd2a53 100644
--- a/CH03/EmojiChat/EmojiChat.csproj
+++ b/CH03/EmojiChat/EmojiChat.csproj
@@ -1,11 +1,7 @@
-
- net6.0
-
-
-
+
diff --git a/CH03/EmojiChat/Startup.cs b/CH03/EmojiChat/Startup.cs
index 16737a3..6b9e048 100644
--- a/CH03/EmojiChat/Startup.cs
+++ b/CH03/EmojiChat/Startup.cs
@@ -6,14 +6,9 @@
namespace EmojiChat;
-public class Startup
+public class Startup(IConfiguration configuration)
{
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
+ public IConfiguration Configuration { get; } = configuration;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
diff --git a/CH03/EmojiChat/WeatherForecast.cs b/CH03/EmojiChat/WeatherForecast.cs
index c96750a..0999053 100644
--- a/CH03/EmojiChat/WeatherForecast.cs
+++ b/CH03/EmojiChat/WeatherForecast.cs
@@ -2,13 +2,7 @@
namespace EmojiChat;
-public class WeatherForecast
+public record WeatherForecast(DateTime Date, int TemperatureC, string Summary)
{
- public DateTime Date { get; set; }
-
- public int TemperatureC { get; set; }
-
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
-
- public string Summary { get; set; }
}
\ No newline at end of file
diff --git a/CH03/HttpHandler/Program.cs b/CH03/HttpHandler/Program.cs
index e0dcab1..c78d6df 100644
--- a/CH03/HttpHandler/Program.cs
+++ b/CH03/HttpHandler/Program.cs
@@ -38,12 +38,13 @@ public static int Main(string[] args)
var client = new RestClient(apiUrl);
var request = new RestRequest(requestPath);
var response = client.Get(request);
- if (response.StatusCode == HttpStatusCode.OK)
+ if (response.StatusCode != HttpStatusCode.OK
+ || response.Content is null)
{
- dynamic obj = JObject.Parse(response.Content);
- var period = obj.properties.periods[0];
- return (double)period.temperature;
+ return null;
}
- return null;
+ dynamic obj = JObject.Parse(response.Content);
+ var period = obj.properties.periods[0];
+ return (double)period.temperature;
}
}
\ No newline at end of file
diff --git a/CH03/HttpHandler/TempReader.csproj b/CH03/HttpHandler/TempReader.csproj
index 872f83e..e60ef3e 100644
--- a/CH03/HttpHandler/TempReader.csproj
+++ b/CH03/HttpHandler/TempReader.csproj
@@ -1,13 +1,12 @@
-
- net6.0
- Exe
-
+
+ Exe
+
-
-
-
-
+
+
+
+
diff --git a/CH03/IfElse/IDatabase.cs b/CH03/IfElse/IDatabase.cs
index 4a2b8c5..26cf54b 100644
--- a/CH03/IfElse/IDatabase.cs
+++ b/CH03/IfElse/IDatabase.cs
@@ -1,4 +1,4 @@
-internal interface IDatabase
+public interface IDatabase
{
string GetCurrentCityByName(string normalizedFirstName, string normalizedLastName);
diff --git a/CH03/IfElse/IfElse.csproj b/CH03/IfElse/IfElse.csproj
index fff7812..c632161 100644
--- a/CH03/IfElse/IfElse.csproj
+++ b/CH03/IfElse/IfElse.csproj
@@ -1,7 +1,3 @@
-
- net6.0
-
-
diff --git a/CH03/IfElse/Person.cs b/CH03/IfElse/Person.cs
index 46dc9ca..b789a25 100644
--- a/CH03/IfElse/Person.cs
+++ b/CH03/IfElse/Person.cs
@@ -1,11 +1,11 @@
-public class Person
+public class Person(int id, string firstName, string lastName, string city, IDatabase db)
{
- public int Id { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string City { get; set; }
+ public int Id { get; set; } = id;
+ public string FirstName { get; set; } = firstName;
+ public string LastName { get; set; } = lastName;
+ public string City { get; set; } = city;
- private readonly IDatabase db;
+ private readonly IDatabase db = db;
public enum UpdateResult
{
diff --git a/CH03/OrderAPI/OrderAPI.csproj b/CH03/OrderAPI/OrderAPI.csproj
index fff7812..c632161 100644
--- a/CH03/OrderAPI/OrderAPI.csproj
+++ b/CH03/OrderAPI/OrderAPI.csproj
@@ -1,7 +1,3 @@
-
- net6.0
-
-
diff --git a/CH03/OrderAPI/PostalAddress.cs b/CH03/OrderAPI/PostalAddress.cs
index e292791..86ea1a3 100644
--- a/CH03/OrderAPI/PostalAddress.cs
+++ b/CH03/OrderAPI/PostalAddress.cs
@@ -1,10 +1,10 @@
-public class PostalAddress
+public class PostalAddress(string firstName, string lastName, string address1, string address2, string city, string zipCode, string notes)
{
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Address1 { get; set; }
- public string Address2 { get; set; }
- public string City { get; set; }
- public string ZipCode { get; set; }
- public string Notes { get; set; }
+ public string FirstName { get; set; } = firstName;
+ public string LastName { get; set; } = lastName;
+ public string Address1 { get; set; } = address1;
+ public string Address2 { get; set; } = address2;
+ public string City { get; set; } = city;
+ public string ZipCode { get; set; } = zipCode;
+ public string Notes { get; set; } = notes;
}
\ No newline at end of file
diff --git a/CH03/OrderAPI/Shipping.cs b/CH03/OrderAPI/Shipping.cs
index 72b8b16..df342d3 100644
--- a/CH03/OrderAPI/Shipping.cs
+++ b/CH03/OrderAPI/Shipping.cs
@@ -1,23 +1,21 @@
using System;
-public class Shipping
+public class Shipping(IDatabase db)
{
- private readonly IDatabase db;
-
public void SetShippingAddress(Guid customerId,
PostalAddress newAddress)
{
- normalizeFields(newAddress);
+ NormalizeFields(newAddress);
db.UpdateShippingAddress(customerId, newAddress);
}
- private void normalizeFields(PostalAddress address)
+ protected static void NormalizeFields(PostalAddress address)
{
address.FirstName = TextHelper.Capitalize(address.FirstName);
address.LastName = TextHelper.Capitalize(address.LastName);
}
- private void normalizeFields2(PostalAddress address)
+ protected static void NormalizeFields2(PostalAddress address)
{
address.FirstName = TextHelper.Capitalize(address.FirstName);
address.LastName = TextHelper.Capitalize(address.LastName);
@@ -25,7 +23,7 @@ private void normalizeFields2(PostalAddress address)
}
}
-internal interface IDatabase
+public interface IDatabase
{
void UpdateShippingAddress(Guid customerId, PostalAddress newAddress);
}
\ No newline at end of file
diff --git a/CH03/OrderAPI/TextHelper.cs b/CH03/OrderAPI/TextHelper.cs
index ca869a7..7eb1e29 100644
--- a/CH03/OrderAPI/TextHelper.cs
+++ b/CH03/OrderAPI/TextHelper.cs
@@ -8,7 +8,7 @@ public static string Capitalize(string text)
{
return text;
}
- return Char.ToUpper(text[0]) + text.Substring(1).ToLower();
+ return Char.ToUpper(text[0]) + text[1..].ToLower();
}
public static string Capitalize(string text,
@@ -20,7 +20,7 @@ public static string Capitalize(string text,
}
if (!everyWord)
{
- return Char.ToUpper(text[0]) + text.Substring(1).ToLower();
+ return char.ToUpper(text[0]) + text[1..].ToLower();
}
string[] words = text.Split(' ');
for (int i = 0; i < words.Length; i++)
@@ -42,9 +42,9 @@ public static string Capitalize(string text,
if (filename)
{
return Char.ToUpperInvariant(text[0])
- + text.Substring(1).ToLowerInvariant();
+ + text[1..].ToLowerInvariant();
}
- return Char.ToUpper(text[0]) + text.Substring(1).ToLower();
+ return char.ToUpper(text[0]) + text[1..].ToLower();
}
string[] words = text.Split(' ');
for (int i = 0; i < words.Length; i++)
@@ -65,7 +65,7 @@ public static string CapitalizeFirstLetter(string text)
{
return text.ToUpper();
}
- return Char.ToUpper(text[0]) + text.Substring(1).ToLower();
+ return Char.ToUpper(text[0]) + text[1..].ToLower();
}
public static string CapitalizeEveryWord(string text)
@@ -91,7 +91,7 @@ public static string FormatFilename(string filename)
else
{
words[n] = Char.ToUpperInvariant(word[0]) +
- word.Substring(1).ToLowerInvariant();
+ word[1..].ToLowerInvariant();
}
}
return String.Join("_", words);
diff --git a/CH03/Shoppidy/Controllers/HomeController.cs b/CH03/Shoppidy/Controllers/HomeController.cs
index 3487d19..a2b4093 100644
--- a/CH03/Shoppidy/Controllers/HomeController.cs
+++ b/CH03/Shoppidy/Controllers/HomeController.cs
@@ -1,37 +1,28 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using System.Threading.Tasks;
+using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Shoppidy.Models;
-namespace Shoppidy.Controllers
+namespace Shoppidy.Controllers;
+
+public class HomeController(ILogger logger) : Controller
{
- public class HomeController : Controller
+ public IActionResult Index()
{
- private readonly ILogger logger;
-
- public HomeController(ILogger logger)
- {
- this.logger = logger;
- }
-
- public IActionResult Index()
- {
- return View();
- }
+ logger.LogDebug("Index()");
+ return View();
+ }
- public IActionResult Privacy()
- {
- return View();
- }
+ public IActionResult Privacy()
+ {
+ logger.LogDebug("Privacy()");
+ return View();
+ }
- [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
- public IActionResult Error()
- {
- return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
- }
+ [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
+ public IActionResult Error()
+ {
+ logger.LogDebug("Error()");
+ return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
diff --git a/CH03/Shoppidy/Controllers/ShipmentFormController.cs b/CH03/Shoppidy/Controllers/ShipmentFormController.cs
index 7789fbe..a6f3815 100644
--- a/CH03/Shoppidy/Controllers/ShipmentFormController.cs
+++ b/CH03/Shoppidy/Controllers/ShipmentFormController.cs
@@ -1,5 +1,4 @@
-using System.Runtime.InteropServices.ComTypes;
-using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc;
public enum ShippingFormValidationResult
{
@@ -10,10 +9,8 @@ public enum ShippingFormValidationResult
ZipCodeDidntMatch,
}
-public class ShipmentFormController : Controller
+public class ShipmentFormController(IShipmentService service) : Controller
{
- private IShipmentService service;
-
public IActionResult Index()
{
return View();
@@ -146,7 +143,7 @@ private bool validate(ShipmentAddress form)
return validationResult == ShippingFormValidationResult.Valid;
}
- private IActionResult shippingFormError(ShipmentAddress form = null)
+ private RedirectToActionResult shippingFormError(ShipmentAddress? form = null)
{
Response.Cookies.Append("shipping_error", "1");
return RedirectToAction("Index", "ShippingForm", form);
diff --git a/CH03/Shoppidy/Models/ErrorViewModel.cs b/CH03/Shoppidy/Models/ErrorViewModel.cs
index dcfcc95..3163854 100644
--- a/CH03/Shoppidy/Models/ErrorViewModel.cs
+++ b/CH03/Shoppidy/Models/ErrorViewModel.cs
@@ -1,11 +1,8 @@
-using System;
+namespace Shoppidy.Models;
-namespace Shoppidy.Models
+public class ErrorViewModel
{
- public class ErrorViewModel
- {
- public string RequestId { get; set; }
+ public string? RequestId { get; set; }
- public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
- }
+ public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
diff --git a/CH03/Shoppidy/Models/IShipmentService.cs b/CH03/Shoppidy/Models/IShipmentService.cs
index 5fab761..3e008ae 100644
--- a/CH03/Shoppidy/Models/IShipmentService.cs
+++ b/CH03/Shoppidy/Models/IShipmentService.cs
@@ -1,4 +1,4 @@
-internal interface IShipmentService
+public interface IShipmentService
{
ShippingFormValidationResult ValidateShippingForm(ShipmentAddress form);
bool SaveShippingInfo(ShipmentAddress form);
diff --git a/CH03/Shoppidy/Models/ShipmentAddress.cs b/CH03/Shoppidy/Models/ShipmentAddress.cs
index 29257db..a13c486 100644
--- a/CH03/Shoppidy/Models/ShipmentAddress.cs
+++ b/CH03/Shoppidy/Models/ShipmentAddress.cs
@@ -2,13 +2,13 @@
public class ShipmentAddress
{
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Address1 { get; set; }
- public string Address2 { get; set; }
- public string City { get; set; }
+ public required string FirstName { get; set; }
+ public required string LastName { get; set; }
+ public required string Address1 { get; set; }
+ public required string Address2 { get; set; }
+ public required string City { get; set; }
[RegularExpression(@"^\s*\d{5}(-\d{4})?\s*$")]
- public string ZipCode { get; set; }
+ public required string ZipCode { get; set; }
}
diff --git a/CH03/Shoppidy/Program.cs b/CH03/Shoppidy/Program.cs
index f3cffac..dc7c34b 100644
--- a/CH03/Shoppidy/Program.cs
+++ b/CH03/Shoppidy/Program.cs
@@ -1,26 +1,19 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
-using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
-using Microsoft.Extensions.Logging;
-namespace Shoppidy
+namespace Shoppidy;
+
+public class Program
{
- public class Program
+ public static void Main(string[] args)
{
- public static void Main(string[] args)
- {
- CreateHostBuilder(args).Build().Run();
- }
-
- public static IHostBuilder CreateHostBuilder(string[] args) =>
- Host.CreateDefaultBuilder(args)
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup();
- });
+ CreateHostBuilder(args).Build().Run();
}
+
+ public static IHostBuilder CreateHostBuilder(string[] args) =>
+ Host.CreateDefaultBuilder(args)
+ .ConfigureWebHostDefaults(webBuilder =>
+ {
+ webBuilder.UseStartup();
+ });
}
diff --git a/CH03/Shoppidy/Shoppidy.csproj b/CH03/Shoppidy/Shoppidy.csproj
index 92605c5..375cccf 100644
--- a/CH03/Shoppidy/Shoppidy.csproj
+++ b/CH03/Shoppidy/Shoppidy.csproj
@@ -1,7 +1,3 @@
-
- netcoreapp3.1
-
-
diff --git a/CH03/Shoppidy/Startup.cs b/CH03/Shoppidy/Startup.cs
index 864096c..42be484 100644
--- a/CH03/Shoppidy/Startup.cs
+++ b/CH03/Shoppidy/Startup.cs
@@ -1,57 +1,46 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
-namespace Shoppidy
+namespace Shoppidy;
+
+public class Startup(IConfiguration configuration)
{
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
+ public IConfiguration Configuration { get; } = configuration;
- public IConfiguration Configuration { get; }
+ // This method gets called by the runtime. Use this method to add services to the container.
+ public void ConfigureServices(IServiceCollection services)
+ {
+ services.AddControllersWithViews();
+ }
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
+ // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
+ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ {
+ if (env.IsDevelopment())
{
- services.AddControllersWithViews();
+ app.UseDeveloperExceptionPage();
}
-
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ else
{
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- else
- {
- app.UseExceptionHandler("/Home/Error");
- // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
- app.UseHsts();
- }
- app.UseHttpsRedirection();
- app.UseStaticFiles();
+ app.UseExceptionHandler("/Home/Error");
+ // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
+ app.UseHsts();
+ }
+ app.UseHttpsRedirection();
+ app.UseStaticFiles();
- app.UseRouting();
+ app.UseRouting();
- app.UseAuthorization();
+ app.UseAuthorization();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllerRoute(
- name: "default",
- pattern: "{controller=Home}/{action=Index}/{id?}");
- });
- }
+ app.UseEndpoints(endpoints =>
+ {
+ endpoints.MapControllerRoute(
+ name: "default",
+ pattern: "{controller=Home}/{action=Index}/{id?}");
+ });
}
}
diff --git a/CH03/TechnicalDebt/TechnicalDebt.csproj b/CH03/TechnicalDebt/TechnicalDebt.csproj
index fff7812..c632161 100644
--- a/CH03/TechnicalDebt/TechnicalDebt.csproj
+++ b/CH03/TechnicalDebt/TechnicalDebt.csproj
@@ -1,7 +1,3 @@
-
- net6.0
-
-
diff --git a/CH03/Twistat/Pages/Callback.cshtml.cs b/CH03/Twistat/Pages/Callback.cshtml.cs
index 684241e..2cda1aa 100644
--- a/CH03/Twistat/Pages/Callback.cshtml.cs
+++ b/CH03/Twistat/Pages/Callback.cshtml.cs
@@ -7,12 +7,12 @@ namespace Twistat.Pages;
public class CallbackModel : PageModel
{
- public IEnumerable Nicks { get; set; }
+ public required IEnumerable Nicks { get; set; }
public void OnGet()
{
// https://localhost:44304/Callback?oauth_token=XhaguQAAAAABFEzEAAABcqR3JuQ&oauth_verifier=focVY8eYIvceblH3rNtPRNrEOtOUP0Pv
- var session = (OAuth.OAuthSession)TempData["session"];
+ var session = TempData["session"] as OAuth.OAuthSession;
session.GetTokens(Request.Query["oauth_verifier"].First());
var tokens = new Tokens()
{
diff --git a/CH03/Twistat/Pages/Error.cshtml.cs b/CH03/Twistat/Pages/Error.cshtml.cs
index f5d6acd..da8822d 100644
--- a/CH03/Twistat/Pages/Error.cshtml.cs
+++ b/CH03/Twistat/Pages/Error.cshtml.cs
@@ -6,21 +6,15 @@
namespace Twistat.Pages;
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
-public class ErrorModel : PageModel
+public class ErrorModel(ILogger logger) : PageModel
{
- public string RequestId { get; set; }
+ public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
- private readonly ILogger logger;
-
- public ErrorModel(ILogger logger)
- {
- this.logger = logger;
- }
-
public void OnGet()
{
+ logger.LogDebug("GET request received");
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
\ No newline at end of file
diff --git a/CH03/Twistat/Pages/Index.cshtml.cs b/CH03/Twistat/Pages/Index.cshtml.cs
index a456b70..16c1ace 100644
--- a/CH03/Twistat/Pages/Index.cshtml.cs
+++ b/CH03/Twistat/Pages/Index.cshtml.cs
@@ -3,16 +3,10 @@
namespace Twistat.Pages;
-public class IndexModel : PageModel
+public class IndexModel(ILogger logger) : PageModel
{
- private readonly ILogger logger;
-
- public IndexModel(ILogger logger)
- {
- this.logger = logger;
- }
-
public void OnGet()
{
+ logger.LogDebug("GET request received");
}
}
\ No newline at end of file
diff --git a/CH03/Twistat/Pages/Login.cshtml.cs b/CH03/Twistat/Pages/Login.cshtml.cs
index 13fd065..819a4c8 100644
--- a/CH03/Twistat/Pages/Login.cshtml.cs
+++ b/CH03/Twistat/Pages/Login.cshtml.cs
@@ -5,19 +5,12 @@
namespace Twistat.Pages;
-public class LoginModel : PageModel
+public class LoginModel(IConfiguration configuration) : PageModel
{
- private readonly IConfiguration config;
-
- public LoginModel(IConfiguration configuration)
- {
- this.config = configuration;
- }
-
public IActionResult OnGet()
{
- string consumerKey = config["Twitter:ConsumerKey"];
- string consumerSecret = config["Twitter:ConsumerSecret"];
+ string consumerKey = configuration["Twitter:ConsumerKey"]!;
+ string consumerSecret = configuration["Twitter:ConsumerSecret"]!;
var session = OAuth.Authorize(consumerKey, consumerSecret,
oauthCallback: $"{Request.Scheme}://{Request.Host}/Callback");
TempData["session"] = session;
diff --git a/CH03/Twistat/Pages/Privacy.cshtml.cs b/CH03/Twistat/Pages/Privacy.cshtml.cs
index 8553210..fcc43b1 100644
--- a/CH03/Twistat/Pages/Privacy.cshtml.cs
+++ b/CH03/Twistat/Pages/Privacy.cshtml.cs
@@ -3,16 +3,10 @@
namespace Twistat.Pages;
-public class PrivacyModel : PageModel
+public class PrivacyModel(ILogger logger) : PageModel
{
- private readonly ILogger logger;
-
- public PrivacyModel(ILogger logger)
- {
- this.logger = logger;
- }
-
public void OnGet()
{
+ logger.LogDebug("GET request received");
}
}
\ No newline at end of file
diff --git a/CH03/Twistat/Startup.cs b/CH03/Twistat/Startup.cs
index ac0d1d2..28a5817 100644
--- a/CH03/Twistat/Startup.cs
+++ b/CH03/Twistat/Startup.cs
@@ -6,14 +6,9 @@
namespace Twistat;
-public class Startup
+public class Startup(IConfiguration configuration)
{
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
+ public IConfiguration Configuration { get; } = configuration;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
diff --git a/CH03/Twistat/Twistat.csproj b/CH03/Twistat/Twistat.csproj
index 0f81324..e753578 100644
--- a/CH03/Twistat/Twistat.csproj
+++ b/CH03/Twistat/Twistat.csproj
@@ -1,13 +1,13 @@
-
- net6.0
- Twistat
-
-
-
-
-
-
-
+
+ Twistat
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/CH03/Twistat/Twitter.cs b/CH03/Twistat/Twitter.cs
index 3effbbb..18234c1 100644
--- a/CH03/Twistat/Twitter.cs
+++ b/CH03/Twistat/Twitter.cs
@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
-public class Twitter
+public class Twitter(TwitterAccessToken accessToken)
{
public static Uri GetAuthorizationUrl(Uri callbackUrl)
{
@@ -17,15 +17,11 @@ public static TwitterAccessToken GetAccessToken(
return new TwitterAccessToken();
}
- public Twitter(TwitterAccessToken accessToken)
- {
- // we should store this somewhere
- }
-
public IEnumerable GetListOfFollowers(
TwitterUserId userId)
{
// no idea how this will work
+ _ = accessToken; // access the access token
yield break;
}
}
diff --git a/CH04/DateUtils/DateUtils.csproj b/CH04/DateUtils/DateUtils.csproj
index fff7812..c632161 100644
--- a/CH04/DateUtils/DateUtils.csproj
+++ b/CH04/DateUtils/DateUtils.csproj
@@ -1,7 +1,3 @@
-
- net6.0
-
-
diff --git a/CH04/DateUtilsTests/Tests.csproj b/CH04/DateUtilsTests/Tests.csproj
index 0938593..8995a15 100644
--- a/CH04/DateUtilsTests/Tests.csproj
+++ b/CH04/DateUtilsTests/Tests.csproj
@@ -1,13 +1,10 @@
-
- net6.0
-
-
-
-
-
-
+
+
+
+
+
diff --git a/CH04/DateUtilsTests/UsernameTest.cs b/CH04/DateUtilsTests/UsernameTest.cs
index 2ed5ee4..965932c 100644
--- a/CH04/DateUtilsTests/UsernameTest.cs
+++ b/CH04/DateUtilsTests/UsernameTest.cs
@@ -10,7 +10,7 @@ internal class UsernameTest
public void ctor_nullUsername_ThrowsArgumentNullException()
{
Assert.Throws(
- () => new Username(null));
+ () => new Username(null!));
}
[TestCase("")]
diff --git a/CH04/Posts/PostService.cs b/CH04/Posts/PostService.cs
index ab3154f..ba60fc6 100644
--- a/CH04/Posts/PostService.cs
+++ b/CH04/Posts/PostService.cs
@@ -7,56 +7,50 @@ namespace Posts;
public class Tag
{
public Guid Id { get; set; }
- public string Title { get; set; }
+ public required string Title { get; set; }
}
-public class PostService
+public class PostService(IPostRepository db)
{
public const int MaxPageSize = 100;
- private readonly IPostRepository db;
- public PostService(IPostRepository db)
+ private List toListTrimmed(byte numberOfItems,
+ IQueryable query)
{
- this.db = db;
+ return [.. query.Take(numberOfItems)];
}
- private IList toListTrimmed(byte numberOfItems,
- IQueryable query)
- {
- return query.Take(numberOfItems).ToList();
- }
-
- public IList GetTrendingTags(byte numberOfItems)
+ public List GetTrendingTags(byte numberOfItems)
{
return toListTrimmed(numberOfItems, db.GetTrendingTagTable());
}
- public IList GetTrendingTagsByTitle(
- byte numberOfItems)
+ public List GetTrendingTagsByTitle(
+ byte numberOfItems)
{
return toListTrimmed(numberOfItems, db.GetTrendingTagTable()
.OrderBy(p => p.Title));
}
- public IList GetYesterdaysTrendingTags(byte numberOfItems)
+ public List GetYesterdaysTrendingTags(byte numberOfItems)
{
return toListTrimmed(numberOfItems,
db.GetYesterdaysTrendingTagTable());
}
- public IList GetTrendingTags(byte numberOfItems,
- bool sortByTitle)
+ public List GetTrendingTags(byte numberOfItems,
+ bool sortByTitle)
{
var query = db.GetTrendingTagTable();
if (sortByTitle)
{
query = query.OrderBy(p => p.Title);
}
- return query.Take(numberOfItems).ToList();
+ return [.. query.Take(numberOfItems)];
}
- public IList GetTrendingTags(byte numberOfItems,
- bool sortByTitle, bool yesterdaysTags)
+ public List GetTrendingTags(byte numberOfItems,
+ bool sortByTitle, bool yesterdaysTags)
{
var query = yesterdaysTags
? db.GetTrendingTagTable()
@@ -65,15 +59,12 @@ public IList GetTrendingTags(byte numberOfItems,
{
query = query.OrderBy(p => p.Title);
}
- return query.Take(numberOfItems).ToList();
+ return [.. query.Take(numberOfItems)];
}
public Tag GetTagDetails(byte numberOfItems, int index)
{
- if (index >= numberOfItems)
- {
- throw new ArgumentOutOfRangeException(nameof(numberOfItems));
- }
+ ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, numberOfItems);
return GetTrendingTags(numberOfItems)[index];
}
}
\ No newline at end of file
diff --git a/CH04/Posts/Posts.csproj b/CH04/Posts/Posts.csproj
index fff7812..c632161 100644
--- a/CH04/Posts/Posts.csproj
+++ b/CH04/Posts/Posts.csproj
@@ -1,7 +1,3 @@
-
- net6.0
-
-
diff --git a/CH04/Summer/Summer.csproj b/CH04/Summer/Summer.csproj
index fff7812..c632161 100644
--- a/CH04/Summer/Summer.csproj
+++ b/CH04/Summer/Summer.csproj
@@ -1,7 +1,3 @@
-
- net6.0
-
-
diff --git a/CH04/User/User.csproj b/CH04/User/User.csproj
index fff7812..c632161 100644
--- a/CH04/User/User.csproj
+++ b/CH04/User/User.csproj
@@ -1,7 +1,3 @@
-
- net6.0
-
-
diff --git a/CH04/User/Username.cs b/CH04/User/Username.cs
index 609af8e..911e53d 100644
--- a/CH04/User/Username.cs
+++ b/CH04/User/Username.cs
@@ -10,23 +10,19 @@ public class Username
public Username(string username)
{
- if (username is null)
- {
- throw new ArgumentNullException(nameof(username));
- }
+ ArgumentNullException.ThrowIfNull(username);
if (!Regex.IsMatch(username, validUsernamePattern))
{
- throw new ArgumentException(nameof(username),
- "Invalid username");
+ throw new ArgumentException("Invalid username", nameof(username));
}
this.Value = username;
}
- public override string ToString() => base.ToString();
+ public override string? ToString() => base.ToString();
public override int GetHashCode() => Value.GetHashCode();
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
return obj is Username other && other.Value == Value;
}
diff --git a/CH05/Blabber.Models/Blabber.Models.csproj b/CH05/Blabber.Models/Blabber.Models.csproj
index edb0b7b..d3d89b6 100644
--- a/CH05/Blabber.Models/Blabber.Models.csproj
+++ b/CH05/Blabber.Models/Blabber.Models.csproj
@@ -1,6 +1,14 @@
netstandard2.0
+ 7.3
+ disable
+
+
+ 1701;1702;IDE0130
+
+
+ 1701;1702;IDE0130
diff --git a/CH05/Blabber/Blabber.csproj b/CH05/Blabber/Blabber.csproj
index 0b9479e..1b2de24 100644
--- a/CH05/Blabber/Blabber.csproj
+++ b/CH05/Blabber/Blabber.csproj
@@ -1,6 +1,6 @@
-
+
Debug
@@ -25,6 +25,8 @@
+ 7.3
+ disable
true
@@ -46,48 +48,49 @@
- ..\..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.dll
+ ..\..\packages\EntityFramework.6.5.1\lib\net45\EntityFramework.dll
- ..\..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.SqlServer.dll
+ ..\..\packages\EntityFramework.6.5.1\lib\net45\EntityFramework.SqlServer.dll
-
- ..\..\packages\Microsoft.Bcl.AsyncInterfaces.7.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll
+
+ ..\..\packages\Microsoft.Bcl.AsyncInterfaces.9.0.9\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll
-
- ..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll
+
+ ..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.4.1.0\lib\net472\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll
-
- ..\..\packages\Microsoft.Extensions.DependencyInjection.7.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.dll
+
+ ..\..\packages\Microsoft.Extensions.DependencyInjection.9.0.9\lib\net462\Microsoft.Extensions.DependencyInjection.dll
-
- ..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.7.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.Abstractions.dll
+
+ ..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.9.0.9\lib\net462\Microsoft.Extensions.DependencyInjection.Abstractions.dll
..\..\packages\Microsoft.Web.Infrastructure.2.0.0\lib\net40\Microsoft.Web.Infrastructure.dll
- ..\..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll
+ ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll
-
- ..\..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.116.0\lib\net46\System.Data.SQLite.dll
+
+ ..\..\packages\System.Data.SQLite.2.0.2\lib\net471\System.Data.SQLite.dll
-
- ..\..\packages\System.Data.SQLite.EF6.1.0.116.0\lib\net46\System.Data.SQLite.EF6.dll
+
+ ..\..\packages\System.Data.SQLite.EF6.2.0.2\lib\net471\System.Data.SQLite.EF6.dll
-
- ..\..\packages\System.Data.SQLite.Linq.1.0.116.0\lib\net46\System.Data.SQLite.Linq.dll
+
+ ..\..\packages\System.Data.SQLite.Linq.1.0.119.0\lib\net46\System.Data.SQLite.Linq.dll
-
- ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll
+
+ ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll
-
- ..\..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll
+
+ ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll
+
@@ -95,22 +98,22 @@
- ..\..\packages\Microsoft.AspNet.WebPages.3.2.9\lib\net45\System.Web.Helpers.dll
+ ..\..\packages\Microsoft.AspNet.WebPages.3.3.0\lib\net45\System.Web.Helpers.dll
-
- ..\..\packages\Microsoft.AspNet.Mvc.5.2.9\lib\net45\System.Web.Mvc.dll
+
+ ..\..\packages\Microsoft.AspNet.Mvc.5.3.0\lib\net45\System.Web.Mvc.dll
- ..\..\packages\Microsoft.AspNet.Razor.3.2.9\lib\net45\System.Web.Razor.dll
+ ..\..\packages\Microsoft.AspNet.Razor.3.3.0\lib\net45\System.Web.Razor.dll
- ..\..\packages\Microsoft.AspNet.WebPages.3.2.9\lib\net45\System.Web.WebPages.dll
+ ..\..\packages\Microsoft.AspNet.WebPages.3.3.0\lib\net45\System.Web.WebPages.dll
- ..\..\packages\Microsoft.AspNet.WebPages.3.2.9\lib\net45\System.Web.WebPages.Deployment.dll
+ ..\..\packages\Microsoft.AspNet.WebPages.3.3.0\lib\net45\System.Web.WebPages.Deployment.dll
- ..\..\packages\Microsoft.AspNet.WebPages.3.2.9\lib\net45\System.Web.WebPages.Razor.dll
+ ..\..\packages\Microsoft.AspNet.WebPages.3.3.0\lib\net45\System.Web.WebPages.Razor.dll
@@ -199,11 +202,11 @@
-
-
-
-
-
+
+
+
+
+
@@ -231,8 +234,8 @@
-
-
+
+
@@ -272,16 +275,16 @@
This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.
-
-
-
-
+
+
+
+
-
-
-
+
+
+