61 lines
2.1 KiB
C#

using System;
using System.Buffers.Text;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace SmallInjectorDemo
{
/// <summary>
/// Static helper class for generating random numbers.
/// </summary>
public static class Helper
{
private const byte ForwardSlashByte = (byte)'/';
private const byte DashByte = (byte)'-';
private const byte PlusByte = (byte)'+';
private const byte UnderscoreByte = (byte)'_';
/// <summary>
/// Encode Base64 string
/// </summary>
public static string EncodeBase64String(this Guid guid)
{
Span<byte> guidBytes = stackalloc byte[16];
Span<byte> encodedBytes = stackalloc byte[24];
MemoryMarshal.TryWrite(guidBytes, ref guid); // write bytes from the Guid
Base64.EncodeToUtf8(guidBytes, encodedBytes, out _, out _);
// replace any characters which are not URL safe
for (var i = 0; i < 22; i++)
{
if (encodedBytes[i] == ForwardSlashByte)
encodedBytes[i] = DashByte;
if (encodedBytes[i] == PlusByte)
encodedBytes[i] = UnderscoreByte;
}
// skip the last two bytes as these will be '==' padding
var final = Encoding.UTF8.GetString(encodedBytes.Slice(0, 22));
return final;
}
/// <summary>
/// Write method string.
/// </summary>
/// <param name="clock">The current clock</param>
/// <param name="id">id of the object</param>
/// <param name="memberName">member name</param>
/// <param name="filepath">file path</param>
/// <returns></returns>
public static string WriteMethodString(IClock clock, string id, [CallerMemberName] string memberName = null, [CallerFilePath] string filepath = null)
{
var classname = Path.GetFileNameWithoutExtension(filepath);
return $"[{clock.CurrentDateTime}] {classname}.{memberName?.TrimStart('.')}".PadRight(30) + $"Id: {id}";
}
}
}