CSharp - Other

Count Words in a Sentence

Quickly determine the number of words in a sentence by splitting the string.

string sentence = "Count the number of words in this sentence.";
int wordCount = sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
Console.WriteLine(wordCount);


Explanation: Using Split with a space delimiter and the RemoveEmptyEntries option ensures accurate word count even with extra spaces.

Create a C# lambda expression from a string (with Roslyn)

Sample code we’ll be trying to achieve

var discountedAlbums = albums.Where(x => x.Quantity > 100);


Building LINQ Expressions by hand

var parameter = Expression.Parameter(typeof(Album), "album");
var comparison = Expression.GreaterThan(Expression.Property(parameter, Type.GetType("ConsoleApp6.Album").GetProperty("Quantity")), Expression.Constant(100));

Func<Album, bool> discountFilterExpression = Expression.Lambda<Func<Album, bool>>(comparison, parameter).Compile();

var discountedAlbums = albums.Where(discountFilterExpression);


From string to lambda with Roslyn

var discountFilter = "album => album.Quantity > 0";
var options = ScriptOptions.Default.AddReferences(typeof(Album).Assembly);
 
Func<Album, bool> discountFilterExpression = await CSharpScript.EvaluateAsync<Func<Album, bool>>(discountFilter, options);
 
var discountedAlbums = albums.Where(discountFilterExpression);

Create a Temp File in the Temp Folder

public static class TempFileCreator
{
    public static void CreateTempFile(string filePath)
    {
        using var sw = new StreamWriter(filePath);

        sw.Write("...");
    }
}


Creating a Temp File Using the GetTempPath() Method

var tempFile = Path.Combine(Path.GetTempPath(),"text.txt");
Console.WriteLine($"Creating temp file: '{tempFile}'");
TempFileCreator.CreateTempFile(tempFile);


Creating a Temp File Using the GetTempFileName() Method

tempFile = Path.GetTempFileName();
Console.WriteLine($"Temp file '{tempFile}' exists? {File.Exists(tempFile)}");
TempFileCreator.CreateTempFile(tempFile);


Creating a Temp File Using the GetFolderPath() Method

var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
tempFile = Path.Combine(appDataPath, "text.txt");
Console.WriteLine($"Creating temp file: '{tempFile}'");
TempFileCreator.CreateTempFile(tempFile);

Create an index on the column - .NET Core

/// <summary>
/// Configures the entity framework mappings for the Modal entity.
/// </summary>
public class ModalConfiguration : IEntityTypeConfiguration<Modal>
{
    /// <summary>
    /// Configures the entity properties and constraints for the Modal entity.
    /// </summary>
    /// <param name="builder">The entity type builder for Modal.</param>
    public void Configure(EntityTypeBuilder<Modal> builder)
    {
        // Create an index on the column
        builder.HasIndex(x => x.Column);
    }
}

Create password protected PDF through PdfSharp

public FileContentResult DownloadPDF()
{
  //Create PDF Document
  PdfDocument document = new PdfDocument();

  //You will have to add Page in PDF Document
  PdfPage page = document.AddPage();
            
  //For drawing in PDF Page you will nedd XGraphics Object
  XGraphics gfx = XGraphics.FromPdfPage(page);
            
  //For Test you will have to define font to be used
  XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
            
  //Finally use XGraphics & font object to draw text in PDF Page
  gfx.DrawString("FileContent", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);

  //Specify file name of the PDF file
  string filename = "FileName.pdf";

  PdfSecuritySettings securitySettings = document.SecuritySettings;

  // Setting one of the passwords automatically sets the security level to 
  // PdfDocumentSecurityLevel.Encrypted128Bit.
  securitySettings.UserPassword = "UserPassword";
  securitySettings.OwnerPassword = "OwnerPassword";

  // Don't use 40 bit encryption unless needed for compatibility reasons
  //securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

  // Restrict some rights.
  securitySettings.PermitAccessibilityExtractContent = false;
  securitySettings.PermitAnnotations = false;
  securitySettings.PermitAssembleDocument = false;
  securitySettings.PermitExtractContent = false;
  securitySettings.PermitFormsFill = true;
  securitySettings.PermitFullQualityPrint = false;
  securitySettings.PermitModifyDocument = true;
  securitySettings.PermitPrint = false;

  //Creates a new Memory stream
  MemoryStream stream = new MemoryStream();
            
  // Saves the document as stream
  document.Save(stream);
  document.Close();

  // Converts the PdfDocument object to byte form.
  byte[] fileBytes = stream.ToArray();

  //System.IO.File.Delete(filename);
  return File(fileBytes, "application/pdf", filename);
}

CsvHelper - Set Header Column via Model

Create ClassMap

void Main()
{
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))
    using (var reader = new StreamReader(stream))
    using (var csv = new CsvWriter(writer))
    {
        var records = new List<Person>
        {
            new Test { DisplayName = "one", Age = 1},
            new Test { DisplayName = "two", Age = 2 },
        };
        
        csv.Configuration.RegisterClassMap<PersonMap>();
        csv.WriteRecords(records);
        
        writer.Flush();
        stream.Position = 0;
        
        Console.WriteLine(reader.ReadToEnd());
    }
}

public class Person
{
    public string DisplayName { get; set; }
    public int Age { get; set; }
}

public sealed class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        Map(m => m.DisplayName).Name("Display Name");
        Map(m => m.Age);
    }
}


Output

Display Name,Age
one,1
two,2

Custom date and time format strings

  1. d - Day of the month (1 to 31)
  2. dd - Day of the month (01 to 31)
  3. ddd - Abbreviated name of the day of the week (Mon to Sun)
  4. dddd - Full name of the day of the week (Monday to Sunday)
  5. f - Tenths of a second
  6. ff - Hundredths of a second
  7. fff - Milliseconds of a second
  8. ffff - Ten thousandths of a second
  9. fffff - Hundred thousandths of a second
  10. ffffff - Millionths of a second
  11. fffffff - Ten millionths of a second
  12. F - Tenths of a second
  13. FF - Hundredths of a second
  14. FFF - Milliseconds of a second
  15. FFFF - Ten thousandths of a second
  16. FFFFF - Hundred thousandths of a second
  17. FFFFFF - Millionths of a second
  18. FFFFFFF - Ten millionths of a second
  19. g - Period or era
  20. gg - Period or era
  21. h - 12-hour (1 to 12)
  22. hh - 12-hour (01 to 12)
  23. H - 24-hour (0 to 23)
  24. HH - 24-hour (00 to 23)
  25. K - Time zone information
  26. m - Minute (0 to 59)
  27. mm - Minute (00 to 59)
  28. M - Month (1 to 12)
  29. MM - Month (01 to 12)
  30. MMM - Abbreviated name of month (Jan to Dec)
  31. MMMM - Full name of month (January to December)
  32. s - Second (0 to 59)
  33. ss - Second (00 to 59)
  34. t - First character of AM/PM designator
  35. tt - AM/PM designator
  36. y - Year (0 to 99)
  37. yy - Year (00 to 99)
  38. yyy - Year (minimum of three digits)
  39. yyyy - Year (four-digit number)
  40. yyyyy - Year (five-digit number)
  41. z - Hours offset from UTC with no leading zeros
  42. zz - Hours offset from UTC with a leading zeros for a single-digit value
  43. zzz - Hours and minutes offset from UTC
  44. : - Time separator
  45. / - Date separator
  46. "string" - Literal string delimiter
  47. 'string' - Literal string delimiter
  48. % - Defines the following character as a custom format specifier
  49. \ - The escape character
  50. Any other character - The character is copied to the result string unchanged

Database providers for DB connections in EF Core

 SQL Server or Azure SQL

.UseSqlServer(connectionString)


Azure Cosmos DB

.UseCosmos(connectionString, databaseName)


SQLite

.UseSqlite(connectionString)


Oracle

.UseOracle(connectionString)

DbContext Pool Performance Monitoring

public class DbContextMonitor
{
    private readonly ILogger<DbContextMonitor> _logger;

    public DbContextMonitor(ILogger<DbContextMonitor> logger)
    {
        _logger = logger;
    }

    public void LogPoolStats(DbContext context)
    {
        var statistics = context.Database.GetService<IDbContextPoolable>();
        if (statistics != null)
        {
            _logger.LogInformation(
                "Pool Size: {PoolSize}, Available: {Available}",
                statistics.MaxPoolSize,
                statistics.AvailableContexts
            );
        }
    }
}


Create a Background Service

public class DbContextMonitoringService : BackgroundService
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ILogger<DbContextMonitoringService> _logger;
    private readonly TimeSpan _interval = TimeSpan.FromMinutes(1); // Adjust as needed


    public DbContextMonitoringService(IServiceProvider serviceProvider, ILogger<DbContextMonitoringService> logger)
    {
        _serviceProvider = serviceProvider;
        _logger = logger;
    }


    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var context = scope.ServiceProvider.GetRequiredService<YourDbContext>();
                var monitor = scope.ServiceProvider.GetRequiredService<DbContextMonitor>();
                monitor.LogPoolStats(context);
            }


            await Task.Delay(_interval, stoppingToken);
        }
    }
}


Register it in Program.cs

builder.Services.AddHostedService<DbContextMonitoringService>(); 
builder.Services.AddSingleton<DbContextMonitor>();

DBContext pooling ASP.NET Core

To achieve high performance in application we should use DbContext pooling. Here instead of creating object each and every time we can use DbContext pooling and when new instance is next requested, that pooled instance is returned instead of setting up a new one. Context pooling allows you to pay context setup costs only once at program startup, rather than continuously.


To enable context pooling, simply replace AddDbContext with AddDbContextPool:

// For smaller applications
builder.Services.AddDbContextPool<ApplicationDbContext>(
    options => options.UseSqlServer(connectionString),
    poolSize: 128
);

// For large applications
builder.Services.AddDbContextPool<ApplicationDbContext>(
    options => options.UseSqlServer(connectionString),
    poolSize: 2048
);


The poolSize parameter of AddDbContextPool sets the maximum number of instances retained by the pool (defaults to 1024). Once poolSize is exceeded, new context instances are not cached and EF falls back to the non-pooling behavior of creating instances on demand.

Declare an Empty Array

Use the “new” Keyword


The Array Initializer Syntax

var myArray = new string[0];


Use an Empty String Literal

var myArray = new string[] { };

or

string[] myArray = { };



Use the Enumerable Class


Use the Empty Method

var myArray = Enumerable.Empty<string>().ToArray();


Use the Repeat Method

var myArray = Enumerable.Repeat("", 0).ToArray();

or

var myArray = Enumerable.Repeat(string.Empty, 0).ToArray();



Use the Array Class


var myArray = Array.Empty<string>();

Delete --- Referrer-Policy

The Referrer-Policy HTTP header controls how much referrer information (sent with the Referer header) should be included with requests. Aside from the HTTP header, you can set this policy in HTML.


Syntax

Referrer-Policy: no-referrer
Referrer-Policy: no-referrer-when-downgrade
Referrer-Policy: origin
Referrer-Policy: origin-when-cross-origin
Referrer-Policy: same-origin
Referrer-Policy: strict-origin
Referrer-Policy: strict-origin-when-cross-origin
Referrer-Policy: unsafe-url


Directives

  • no-referrer - The Referrer header will be omitted: sent requests do not include any referrer information.
  • no-referrer-when-downgrade - Send the origin, path, and query string in Referrer when the protocol security level stays the same or improves (HTTP → HTTP, HTTP → HTTPS, HTTPS → HTTPS). Don't send the Referrer header for requests to less secure destinations (HTTPS → HTTP, HTTPS → file).
  • origin - Send only the origin in the Referrer header. For example, a document at https://example.com/page.html will send the referrer https://example.com/.
  • origin-when-cross-origin - When performing a same-origin request to the same protocol level (HTTP → HTTP, HTTPS → HTTPS), send the origin, path, and query string. Send only the origin for cross origin requests and requests to less secure destinations (HTTPS → HTTP).
  • same-origin - Send the origin, path, and query string for same-origin requests. Don't send the Referrer header for cross-origin requests.
  • strict-origin - Send only the origin when the protocol security level stays the same (HTTPS → HTTPS). Don't send the Referrer header to less secure destinations (HTTPS → HTTP).
  • strict-origin-when-cross-origin (default) - Send the origin, path, and query string when performing a same-origin request. For cross-origin requests send the origin (only) when the protocol security level stays same (HTTPS → HTTPS). Don't send the Referrer header to less secure destinations (HTTPS → HTTP).


Integration with HTML

You can also set referrer policies inside HTML. For example, you can set the referrer policy for the entire document with a <meta> element with a name of referrer:

<meta name="referrer" content="origin" />


You can specify the referrerpolicy attribute on <a>, <area>, <img>, <iframe>, <script>, or <link> elements to set referrer policies for individual requests:

<a href="http://example.com" referrerpolicy="origin">…</a>


Alternatively, you can set a noreferrer link relation on an a, area, or link elements:

<a href="http://example.com" rel="noreferrer">…</a>