CSharp - Other

ASP.NET Core - Work with a database

Required nuget

  1. Microsoft.EntityFrameworkCore
  2. Microsoft.EntityFrameworkCore.SqlServer


public class DatabaseNameContext : DbContext
{
  public DatabaseNameContext (DbContextOptions<MvcMovieContext> options) : base(options)
  {

  }

  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  {
    optionsBuilder.UseSqlServer("DatabaseConnectionString");
  }

  public DbSet<ModelName> Models{ get; set; }

  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
    base.OnModelCreating(modelBuilder);
  }
}


appsettings.json

{
  "ConnectionStrings": {
    "DatabaseNameContext": "DatabaseConnectionString"
  }   
}


Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<DatabaseNameContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DatabaseNameContext"))));

ASP.NET MVC Web.config move AppSettings to separate file

Create a new config file name PrivateSettings.config.

<appSettings>
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>


Add the path to your extra appSettings file to the web.config appSettings tag.

<appSettings file="PrivateSettings.config">
  ...
</appSetting>

ASP.NET Web Application (.NET Framework) - error: the details of the application error from being viewed remotely

Turn off the custom errors in Web.config file.


<configuration>
  <system.web>
    <customErrors mode="Off"/>
  </system.web>
</configuration>

ASP.NET Web Application (.NET Framework) - How to remove returnurl from url?

Add this to your Global.asax file.


public class MvcApplication : HttpApplication {

  private const string ReturnUrlRegexPattern = @"\?ReturnUrl=.*$";

  public MvcApplication()
  {
    PreSendRequestHeaders += MvcApplicationOnPreSendRequestHeaders;
  }

  private void MvcApplicationOnPreSendRequestHeaders(object sender, EventArgs e)
  {
    string redirectUrl = Response.RedirectLocation;

    if (string.IsNullOrEmpty(redirectUrl) || !Regex.IsMatch(redirectUrl, ReturnUrlRegexPattern))
    {
      return;
    }

    Response.RedirectLocation = Regex.Replace(redirectUrl, ReturnUrlRegexPattern, string.Empty);
  }
}

ASP.NET Web Application (.NET Framework) - Object reference not set to an instance of an object in _Layout.cshtml after updated packages

Replacing ScriptBundle with Bundle in App_Start/BundleConfig.cs.

ASP.NET Web Application (.NET Framework) - There is already an open DataReader associated with this Command which must be closed first

Add MultipleActiveResultSets=true to the provider part of your connection string (where Data Source, Initial Catalog, etc. are specified).


Example :

<connectionStrings>
    <add name="Context" connectionString="Data Source=localhost;Initial Catalog=DBName;User ID=username;Password=password;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
</connectionStrings>

Avoid Mixing LINQ and Traditional Loops

Mixing LINQ and traditional loops can lead to confusing and hard-to-maintain code. Choose one approach and stick with it within a method:


// Avoid mixing like this:
var query = users.Where(u => u.IsActive);
foreach (var user in query)
{
    if (user.Age > 30)
    {
        // Do something
    }
}


// Prefer this:
var relevantUsers = users.Where(u => u.IsActive && u.Age > 30);
foreach (var user in relevantUsers)
{
    // Do something
}

Avoid using ref and out parameters unless absolutely necessary

Do

void DoSomething(int x, out int y)
{
    y = x * 2;
}


Don't

void DoSomething(ref int x, out int y)
{
    x = 10;
    y = 20;
}

Avoid using var unless it clearly improves readability

Do

int x = 10;
string y = "hello";


Don't

var x = 10;
var y = "hello";

Basic Expression Tree Example

This example demonstrates how to create a simple expression like x => x + 2 dynamically.

using System;
using System.Linq.Expressions;

class Program
{
    static void Main()
    {
        // Parameter: x
        ParameterExpression param = Expression.Parameter(typeof(int), "x");

        // Constant: 2
        ConstantExpression constant = Expression.Constant(2, typeof(int));

        // Add operation: x + 2
        BinaryExpression addExpression = Expression.Add(param, constant);

        // Lambda: x => x + 2
        var lambda = Expression.Lambda<Func<int, int>>(addExpression, param);

        // Compile the lambda
        var compiledFunc = lambda.Compile();

        // Invoke the lambda
        int result = compiledFunc(5);
        Console.WriteLine($"Result of x + 2 when x = 5: {result}"); // Output: 7
    }
}

Be Careful with Multiple Enumerations

Enumerating the same LINQ query multiple times can lead to performance issues. Store the results in a list if you need to use them multiple times:


// Bad: Enumerates twice
var count = query.Count();
var firstItem = query.FirstOrDefault();

// Good: Enumerates once
var results = query.ToList();
var count = results.Count;
var firstItem = results.FirstOrDefault();

Be Cautious with Large Collections

For very large collections or performance-critical sections, consider using traditional loops:


// For large collections, this might be faster:
var count = 0;
foreach (var item in largeCollection)
{
    if (item.SomeProperty > 100)
    {
        count++;
    }
}

// Instead of:
var count = largeCollection.Count(item => item.SomeProperty > 100);