Could not find a part of the path ... bin\roslyn\csc.exe
Run this in the Package Manager Console:
Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r
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.
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);
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);
/// <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); } }
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); }
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
public static class DateTimeExtensions { public static bool IsBetween(this DateTime dateTime, DateTime startDate, DateTime endDate) { return dateTime >= startDate && dateTime <= endDate; } public static DateTime StartOfDay(this DateTime dateTime) { return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, dateTime.Kind); } public static DateTime EndOfDay(this DateTime dateTime) { return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 23, 59, 59, 999, dateTime.Kind); } public static int GetAge(this DateTime birthDate) { var today = DateTime.Today; var age = today.Year - birthDate.Year; if (birthDate.Date > today.AddYears(-age)) age--; return age; } public static bool IsWeekend(this DateTime dateTime) { return dateTime.DayOfWeek == DayOfWeek.Saturday || dateTime.DayOfWeek == DayOfWeek.Sunday; } public static DateTime NextBusinessDay(this DateTime dateTime) { var nextDay = dateTime.AddDays(1); while (nextDay.IsWeekend()) { nextDay = nextDay.AddDays(1); } return nextDay; } }
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>();
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.