Saturday, 18 January 2025

Monitoring User Secrets inside Blazor

This article shows how you can add User Secrets for a Blazor app, or other related .NET client technology supporting them. User secrets are stored on the individual computer, so one do not have to expose them to others. They can still be shared between different people if they are told what the secrets are, but is practical in many cases where one for example do not want to expose the secrets such as a password, by checking it into
source code repositories. This is due to the fact as mentioned that the user secrets are as noted saved on the individual computer.

User secrets was added in .NET Core 1.0, already released in 2016. Not all developers are familiar with them. Inside Visual Studio 2022, you can right click on the Project of a solution and choose Manage User Secrets. When you choose that option, a file called secrets.json is opened. The file location for this file is shown if you hover over the file. The file location is saved here:

  
    %APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json
  
  
You can find the id here, the user_secrets_id, inside the project file (the .csproj file).
Example of such a setting below:
  
  <Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UserSecretsId>339fab44-57cf-400c-89f9-46e037bb0392</UserSecretsId>
  </PropertyGroup>

</Project>

  

Let's first look at the way we can set up user secrets inside a startup file for the application. Note the usage of reloadOnChange set to true. And adding the user secrets as a singleton service wrapped inside IOptionsMonitor.

Program.cs



builder.Configuration.Sources.Clear();
builder.Configuration
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
        .AddUserSecrets(Assembly.GetEntryAssembly()!, optional:false, reloadOnChange: true)
        .AddEnvironmentVariables();

builder.Services.Configure<ModelSecrets>(builder.Configuration.GetSection("ModelSecrets"));
builder.Services.AddSingleton<IOptionsMonitor<ModelSecrets>>, OptionsMonitor<ModelSecrets>>();



The Model secrets class looks like the following.



namespace StoringSecrets
{
    public class ModelSecrets
    {
        public string ApiKey { get; set; } = string.Empty;
    }
}


Home.razor.cs

Let's then look how we can fetch values from the user secrets. The code file for a file Home.razor is put in a file of its own, Home.razor.cs


using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Options;

namespace ToreAurstadIt.StoringSecrets.Components.Pages
{
    public partial class Home
    {
        [Inject]
        public required IOptionsMonitor<ModelSecrets> ModelSecretsMonitor { get; set; }

        public ModelSecrets? ModelSecrets  { get; set; }

        protected override async Task OnInitializedAsync()
        {
            ModelSecrets = ModelSecretsMonitor.CurrentValue;
            ModelSecretsMonitor.OnChange(updatedSecrets =>
            {
                ModelSecrets = updatedSecrets;
                InvokeAsync(StateHasChanged);

            });
            await Task.CompletedTask;
        }
    }
}

Note that IOptionsMonitor<ModelSecrets> is injected here and that in the OnInitializedAsync method, the injected value uses the OnChange method and and action callback then sets the value of the ModelSecrets and calls InvokeAsync method with StateHasChanged. We output the CurrentValue into the razor view of the Blazor app.

Home.razor



@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

Your user secret is: 
<div>
    @ModelSecrets?.ApiKey
</div>


The secret.json file looks like this:

secrets.json



{
  "ModelSecrets": {
    "ApiKey": "SAMPLE_VALUE_UPDATE_9"
  }
}


A small app shows how this can be done, by changing the user secrets file and then reloading the page, changes should be immediately seen:

Calculating day of the week from Lewis Carrol's algorithm

This article will present the Lewis Carrol's algorithm to calculate the day of the week.

Lewis Carrol was a mathematician and logician at Oxford University. He is a wellknown name today for his children novels such as "Alice in Wonderland", published in 1871.

The name Lewis Carrol is a pseudonym, his real name was Charles Ludwidge Dodgson. The algorithm presented here was released in 1883.

Let's look at the algorithm next for calculating the day of week. Please note that this algorithm got inaccuracies for leap years and february, it is about 90-95% correct for all dates. In many cases it will give correct results for other dates. The algorithm presented here is for dates after September 12, 1752 due to changes in our calendar system at that date.

Construct a Number n consisting of four parts where

n = CCYYMMDD | CC = century, YY = year, MM = month , DD = day

For example, the date 18th of January, 2025 is written as

n = 202501818 , CC = 20, YY = 25, MM = 01, DD = 18

The calculation will sum up the contributions from the numbers into a sum S as :

S = Sum_cc + Sum_yy + Sum_mm + Sum_dd

The sum S is then taken the modulo of 7, where the number 0 means Sunday and number 6 means Saturday. The day and week is therefore the modulo 7 of S where starting from Sunday, the remainder from S mod 7 is the weekday, starting with index 0 for Monday.

Let's look at the different part sums next.

Sum_cc is calculated as the 3 subtracted by the century modulo 4 and this is multiplied by two. Sum_yy is the year divided by 12 plus the year modulo 12 and the year divided by 4. Sum_mm is defined as the month looked up in a lookup table of values shown in the source code. Sum_dd is just the date of the month.

The summmation looks like this:


private int DayOfWeekLevisCarrol(int date){
 int century = date / 1_000_000;
 int year = (date / 10_000) % 100;
 int month = (date / 100) % 100;
 int dayValue = (date % 100); 
 int[] monthValues = [0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 12]; 
 int centuryValue = (3-(century % 4))*2;
 int yearValue = (year/12) + (year % 12) + ((year % 12)/4);
 int monthValue = monthValues[month-1]; 
 var sumValues= (centuryValue+yearValue+monthValue+dayValue) % 7;
 return sumValues;
}


This helper method shows the weekday presented as text:


public string WeekDayLevisCarrol(int date) => DayOfWeekLevisCarrol(date) switch {
 0 => "Sunday",
 1 => "Monday",
 2 => "Tuesday",
 3 => "Wednesday",
 4 => "Thursday",
 5 => "Friday",
 6 => "Saturday",
 _ => "Impossible"	
};


A more compressed way of expressing this is the following:


/// <summary>
/// Calculates the day of the week using Lewis Carroll's method.
/// </summary>
/// <param name="date">The date in yyyymmdd format.</param>
/// <returns>The day of the week as an integer (0 for Sunday, 1 for Monday, etc.).</returns>
private int DayOfWeekLevisCarrolV2(int date) =>
    ((3 - (date / 1_000_000 % 4)) * 2 +
    (date / 10_000 % 100 / 12) + (date / 10_000 % 100 % 12) + ((date / 10_000 % 100 % 12) / 4) +
    new int[] { 0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 12 }[(date / 100 % 100) - 1] +
    (date % 100)) % 7;



Running the metod for today (I used 18th of January 2025):

void Main()
{
	int todayDate = int.Parse(DateTime.Today.ToString("yyyyMMdd"));
	string todayWeekdate = WeekDayLevisCarrol(todayDate);
	Console.WriteLine($"Levis-Carrol's method calculated weekday for {DateTime.Today.ToShortDateString()} written as number {todayDate} is: {todayWeekdate}");
}


Output is:

Levis-Carrol's method calculated weekday for 18.01.2025 written as number 20250118 is: Saturday As noted, this algorithm is about 90-95% correct since it is not precise in leap years and in February. There are more precise calculation algorithms today, the algorithm is to be considered a crude approach and more modern algorithms exists today. In .NET, the calculation of the weekday is done inside the DateTime struct calculated from the start of Epoch at year 1 and there are precise calculations considering shifts in calendars and leap years, so of course you should use DayOfWeek of a DateTime in .NET. But it is a fun trivia that the author of "Alice in Wonderland" was a also a noted mathematician and according to history, he calculated weekdays for dates in few seconds using this algorithm, often being correct.

Monday, 13 January 2025

Diophantine linear equation solver in C#

Diophantine linear equations are equations of two unkowns on the format

ax + by = c

The code below shows how we can solve Diophantine equations with a sample equation :

7x - 9y = 3

DiophantineSolver.cs



class Program
{
	static void Main()
	{
		int a = 7,
		b = -9, 
		c = 3;
		DiophantineSolver.DiophantineSolution solution = DiophantineSolver.ExtendedGcd(a, b, c);

		Console.WriteLine(solution.ToString());
	}
}

/// <summary>
/// Class containing methods to solve Diophantine equations using the Extended Euclidean Algorithm.
/// </summary>
class DiophantineSolver
{
	/// <summary>
	/// Struct to hold the solution of a Diophantine equation.
	/// </summary>
	public struct DiophantineSolution
	{
		/// <summary>
		/// Indicates whether the equation has a solution.
		/// </summary>
		public bool IsSolvable { get; set; }

		/// <summary>
		/// X0, a articular solution for variable x, or null if no solution exists. Other solutions of X can be derived from this.
		/// </summary>
		public int? X0 { get; set; }

		/// <summary>
		/// Y0, a particular solution, or null if no solution exists. Other solutions of Y can be derived from this.
		/// </summary>
		public int? Y0 { get; set; }

		/// <summary>
		/// The coefficient of x in the equation.
		/// </summary>
		public readonly int A;

		/// <summary>
		/// The coefficient of y in the equation.
		/// </summary>
		public readonly int B;

		/// <summary>
		/// The constant term in the equation.
		/// </summary>
		public readonly int C;
		
		/// <summary>D: The greatest common divisor gcd(a,b) = d</summary>
		/// <remarks>Solutions to the Diophantine linear equation exists only if C|D: D is divisible by C.</remarks>
		public readonly int? D;

		/// <summary>
		/// Initializes a new instance of the DiophantineSolution struct.
		/// </summary>
		/// <param name="isSolvable">Indicates whether the equation has a solution.</param>
		/// <param name="x0">The x-coordinate of the particular solution.</param>
		/// <param name="y0">The y-coordinate of the particular solution.</param>
		/// <param name="a">The coefficient of x in the equation.</param>
		/// <param name="b">The coefficient of y in the equation.</param>
		/// <param name="c">The constant term in the equation.</param>
		/// <param name="d">The d= gcd(a,b) greatest common divisor found for a and b</param>
		public DiophantineSolution(bool isSolvable, int? x0, int? y0, int a, int b, int c, int d)
		{
			IsSolvable = isSolvable;
			X0 = x0;
			Y0 = y0;
			A = a;
			B = b;
			C = c;
			D = d;
		}

		/// <summary>
		/// Returns a string representation of the solution.
		/// </summary>
		/// <returns>A string representation of the solution.</returns>
		public override string ToString()
		{
			if (IsSolvable)
			{
				string result = $"""
				Diophantine Linear Equation Solver result for equation 
				AX + BY = C
				{A}x + {B}y = {C} 
				A={A}, B={B}, C={C}
				Greatest common divisor :
				d = gcd(a,b) = {D?.ToString() ?? "No gcd found"}
				Solutions exists? {IsSolvable}, since d|c = {D}|{C}: {C} is divisible by {D}
				Particular solution A(x0) + B(y0) = C
				x0 = {X0}, y0 = {Y0}
				({A}*{X0}) + ({B}*{Y0}) = {C}
				({A * X0}) + ({B * Y0}) = {C}
				Generalized solution:				
				{GetParameterizedSolution()}
				Additional solutions:
				""";
				if (D > 0)
				{
					for (int t = 1; t <= 3; t++)
					{
						int xn = X0!.Value + (B / D!.Value) * t;
						int yn = Y0!.Value - (A / D!.Value) * t;
						result += $"\nSolution {t}: x = {xn}, y = {yn} (t = {t}) , since : ({xn}*{X0}) + ({yn}*{Y0}) = ({xn * X0}) + ({yn * Y0}) = {C}";
					}
				}
				else {
					result += "No additional solutions exists"; 
				}
				return result;
			}
			else
			{
				return $"Diophantine Linear Equation Solver result\nNo solution exists. d = gcd(a,b) = {D}. Solution exists if: {C}|{D}. This gives a remainder of {C % D} != 0. {C} is not divisible by {D}. C = {C} = n*D + r = ({C / D}*{D}) + {C % D}.";
			}
		}

		/// <summary>
		/// Returns the parameterized solution expression as a string.
		/// </summary>
		/// <returns>A string representation of the parameterized solution.</returns>
		public string GetParameterizedSolution()
		{
			if (D == 0){
				return "No solution exists, so there is not general parameterized solution";
			}
			string generalEquation = "x' = x_0 + (B/D), y' = y_0 - (A/D)";
			return $"{generalEquation}{Environment.NewLine}x' = {X0} + ({B}/{D})t, y' = {Y0} - ({A}/{D})t, where t is any integer";
		}
	}

	/// <summary>
	/// Solves the Diophantine equation ax + by = c using the Extended Euclidean Algorithm.
	/// </summary>
	/// <param name="a">The coefficient of x.</param>
	/// <param name="b">The coefficient of y.</param>
	/// <param name="c">The constant term.</param>
	/// <returns>A DiophantineSolution struct containing the solution.</returns>
	public static DiophantineSolution ExtendedGcd(int a, int b, int c)
	{
		int X0, Y0;
		int gcd = ExtendedGcd(a, b, out X0, out Y0);

		if (c % gcd != 0)
		{
			return new DiophantineSolution(false, null, null, a, b, c, gcd);
		}
		else
		{
			int x = X0 * (c / gcd);
			int y = Y0 * (c / gcd);
			return new DiophantineSolution(true, x, y, a, b, c, gcd);
		}
	}

	/// <summary>
	/// Computes the greatest common divisor of a and b, and finds coefficients X0 and Y0 such that a*X0 + b*Y0 = gcd(a, b).
	/// </summary>
	/// <param name="a">The first integer.</param>
	/// <param name="b">The second integer.</param>
	/// <param name="X0">The coefficient of a in the linear combination.</param>
	/// <param="Y0">The coefficient of b in the linear combination.</param>
	/// <returns>The greatest common divisor of a and b.</returns>
	private static int ExtendedGcd(int a, int b, out int X0, out int Y0)
	{
		if (b == 0)
		{
			X0 = 1;
			Y0 = 0;
			return a; // Base case: gcd(a, 0) = a
		}

		int X1, Y1;
		int gcd = ExtendedGcd(b, a % b, out X1, out Y1); // Recursive call

		X0 = Y1; // Back substitution: X0 = Y1
		Y0 = X1 - (a / b) * Y1; // Back substitution: Y0 = X1 - (a / b) * Y1

		return gcd; // Return the gcd
	}
}



The extended Euclidean algorithm calculates the greatest common divisor and in the recursion also applies back substitution. The coefficients X0 and Y0 founds satisfy the equation :

(a · X0) + (b · Y0) = gcd(a, b)



That is, a linear combination of the original integers a and b equaling the gcd(a,b). The output of running the code shown above is:


Diophantine Linear Equation Solver result for equation
AX + BY = C
7x + -9y = 3
A=7, B=-9, C=3
Greatest common divisor :
d = gcd(a,b) = 1
Solutions exists? True, since d|c = 1|3: 3 is divisible by 1
Particular solution A(x0) + B(y0) = C
x0 = 12, y0 = 9
(7*12) + (-9*9) = 3
(84) + (-81) = 3
Generalized solution:               
x' = x_0 + (B/D), y' = y_0 - (A/D)
x' = 12 + (-9/1)t, y' = 9 - (7/1)t, where t is any integer
Additional solutions:
Solution 1: x = 3, y = 2 (t = 1) , since : (3*12) + (2*9) = (36) + (18) = 3
Solution 2: x = -6, y = -5 (t = 2) , since : (-6*12) + (-5*9) = (-72) + (-45) = 3
Solution 3: x = -15, y = -12 (t = 3) , since : (-15*12) + (-12*9) = (-180) + (-108) = 3

So an example of a solution of the equation : 7x -9y = 3 Is: x = 12, y = 9, since (7*12) - (9*9) = 84 - 81 = 3. Note that once you have found a solution to a linear Diophantine equation, you can found infinite other solutions. More formally:

Diophantine Equation (Linear) Definition and Solvability

A linear Diophantine equation is an equation of the form:

(a · x) + (b · y) = c

where a, b, and c are integers, and x and y are unknown integers.

Solvability

The linear Diophantine equation (a · x) + (b · y) = c has integer solutions if and only if the greatest common divisor (gcd) of a and b divides c. In mathematical notation:

d is gcd. d|c => gcd(a, b) | c

If gcd(a, b) divides c (it is common to use d to notify gcd as a short term notation), then there exist integer solutions x and y such that:

(a · x) + (b · y) = c

Otherwise, there are no integer solutions.