European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core 10.0 Hosting - HostForLIFE :: Ten Blazor Coding Errors I Observe in Actual Projects (and How to Prevent Them)

clock December 22, 2025 07:38 by author Peter

Although Blazor is an effective framework for creating contemporary C# online applications, I frequently observe the same errors that impair security, performance, and maintainability in real world projects. These are the ten most frequent Blazor coding errors I see in production, along with suggestions for fixing them, based on my years of experience working on enterprise and SaaS Blazor apps.

1. Putting Business Logic Directly in .razor Files

Many Blazor apps start simple, but over time .razor files turn into massive files full of logic.

Why it’s a problem?
Hard to test

  • Difficult to maintain
  • Poor separation of concerns
  • Better approach

Move logic to code-behind files ( .razor.cs )

Or use service classes and inject them into components

"Razor files should focus on UI, not business rules."

2. Ignoring Proper Naming Conventions
Inconsistent naming is one of the fastest ways to make a Blazor codebase confusing.

Common mistakes
Components named test.razor , page1.razor

Methods like DoStuff() or Handle()

Better approach

Use clear, intention-revealing names
InvoiceList.razor , UserProfileCard.razor

Follow consistent casing and suffix rules

Good naming is not optional — it’s a productivity multiplier.

3. Overusing @code Blocks Instead of Reusable Services

Developers often copy and paste logic between components.

Why these hurts

  • Code duplication
  • Bugs fixed in one place but not others

Better approach
Extract shared logic into services

Register them using dependency injection

Blazor’s DI system is there for a reason — use it.

4. Incorrect State Management
State bugs are subtle and painful.

Common issues

  • Relying too much on static variables
  • Losing state on refresh (especially in WASM)
  • Confusing scoped vs singleton services

Better approach

  • Understand component lifecycle
  • Use scoped services wisely
  • Persist important state explicitly

State management should be intentional, not accidental.

5. Calling APIs Directly from Components Everywhere
Calling APIs inside every component leads to tight coupling.

Why it’s risky

  • Hard to mock
  • Hard to refactor
  • Poor error handling consistency

Better approach

  • Create API service layers
  • Centralize error handling and retries

Your components will become cleaner instantly.

6. Not Handling Errors Gracefully
Unhandled exceptions in Blazor can break the entire UI.

Common mistakes

  • No try/catch around async calls
  • No user-friendly error messages

Better approach

  • Wrap async operations carefully
  • Use error boundaries
  • Log errors properly

Production apps must fail gracefully .

7. Poor Folder Structure
Flat or random folder structures don’t scale.

What I often see

  • All components in one folder
  • No separation between pages, shared components, and features

Better approach

  • Feature-based folders
  • Clear separation for:
    • Pages
    • Components
    • Services
    • Models

Structure is a form of documentation.

8. Ignoring Performance Basics
Blazor performance issues are usually self-inflicted.

Common mistakes

  • Heavy OnAfterRenderAsync
  • Unnecessary re-rendering
  • Large component trees

Better approach

  • Use @key correctly
  • Minimize re-renders
  • Measure before optimizing

Small changes can have a huge impact.

9. Hardcoding Configuration Values
Hardcoded URLs, keys, and flags appear far too often.

Why this is dangerous

  • Security risks
  • Difficult environment changes

Better approach

  • Use appsettings.json
  • Environment-specific configuration
  • Secure secrets properly

Configuration should never live in UI code.

10. Treating Blazor Like JavaScript Frameworks
Blazor is not React or Angular .
Common mistake

  • Forcing JS-style patterns into Blazor
  • Ignoring C# and .NET strengths

Better approach

  • Embrace strong typing
  • Use C# patterns
  • Leverage .NET libraries

Blazor shines when you use it the Blazor way .

Final Thoughts
Most Blazor problems are not framework issues they’re coding standard issues .

Once you apply consistent rules for:

  • Naming
  • Structure
  • State
  • Error handling
  • Performance

your Blazor apps become cleaner, faster, and easier to scale.



European ASP.NET Core 10.0 Hosting - HostForLIFE :: How Can the Performance of Entity Framework Core Queries Be Enhanced?

clock December 12, 2025 08:32 by author Peter

With Entity Framework Core (EF Core), a potent ORM for.NET applications, developers may use LINQ rather than SQL to communicate with databases. However, EF Core queries can become slow if they are not utilized carefully, particularly when dealing with big tables and intricate interactions. The good news? You may greatly enhance EF Core performance with a variety of easy methods. This post will teach you how to improve your EF Core queries and speed up your.NET apps using simple, natural language.

Use AsNoTracking for Read-Only Queries
Tracking changes adds overhead. If you’re only reading data, disable tracking.

Example (Slow)
var users = await _context.Users.ToListAsync();

Optimized
var users = await _context.Users.AsNoTracking().ToListAsync();

Why It Helps?

  • Reduces memory usage
  • Improves query execution speed
  • Recommended for all read-only operations

Select Only the Columns You Need (Projections)

Fetching entire entities loads unnecessary columns.

Slow Query
var users = await _context.Users.ToListAsync();


Efficient Query
var users = await _context.Users
    .Select(u => new { u.Id, u.Name })
    .ToListAsync();


Benefits

  • Smaller payload
  • Faster network transfer
  • Reduced materialization overhead

Use Pagination for Large Result Sets

Never return thousands of rows at once.

Example

var page = 1;
var pageSize = 20;

var users = await _context.Users
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync();


Why It Helps?

  • Reduces memory usage
  • Prevents slow UI loading

Avoid N+1 Query Problems with Include
If you load related data in a loop, EF will run multiple queries.

Bad (N+1 queries)
var users = await _context.Users.ToListAsync();
foreach (var user in users)
{
    var orders = user.Orders; // triggers additional queries
}


Good
var users = await _context.Users
    .Include(u => u.Orders)
    .ToListAsync();

Why It Matters?
Prevents unnecessary round trips to the database

Use Filter Before Include (Important)

Filtering after Include loads unnecessary data.

Inefficient
var users = await _context.Users
    .Include(u => u.Orders)
    .Where(u => u.IsActive)
    .ToListAsync();


Optimized

var users = await _context.Users
    .Where(u => u.IsActive)
    .Include(u => u.Orders)
    .ToListAsync();


Why This Helps?

  • Does not fetch extra records
  • Reduces memory and improves SQL execution

Index Database Columns Properly
Indexes drastically improve filtering and lookups.

Add Index in Entity

[Index(nameof(Email), IsUnique = true)]
public class User { ... }


Performance Impact

  • Faster queries on WHERE clauses
  • Better JOIN performance

Avoid Client Evaluation (Let Database Do the Work)
EF Core may switch to client-side evaluation if query contains unsupported logic.

Bad
var users = await _context.Users
    .Where(u => SomeCSharpFunction(u.Name)) // runs on client
    .ToListAsync();


Good
var users = await _context.Users
    .Where(u => u.Name.Contains(search)) // SQL compatible
    .ToListAsync();

Why This Matters?

  • Client-side evaluation slows down performance
  • Database engines are optimized for filtering

Use Compiled Queries for Frequently Used Queries

If a query runs millions of times, precompile it.

Example
static readonly Func<AppDbContext, int, Task<User>> GetUserById =
    EF.CompileAsyncQuery((AppDbContext ctx, int id) =>
        ctx.Users.FirstOrDefault(u => u.Id == id));

Why It Helps

  • Reduces overhead of query translation
  • Useful for high-performance APIs

Avoid Using Lazy Loading (Prefer Explicit Loading)

Lazy loading causes hidden queries.

Bad
var user = await _context.Users.FirstAsync();
var orders = user.Orders; // triggers separate query

Good
var user = await _context.Users
    .Include(u => u.Orders)
    .FirstAsync();


Why

  • Lazy loading = more queries
  • Explicit loading = predictable performance


Keep Queries Simple and Use Raw SQL When Necessary
Sometimes LINQ creates inefficient SQL.

Example
var data = await _context.Users
    .FromSqlRaw("SELECT * FROM Users WHERE IsActive = 1")
    .ToListAsync();

When Useful

  •     Extremely complex queries
  •     Performance-critical reporting

Cache Frequently Requested Data
Use caching for data that rarely changes.
var cacheKey = "ActiveUsers";
if (!_memoryCache.TryGetValue(cacheKey, out List<User> users))
{
    users = await _context.Users.Where(u => u.IsActive).ToListAsync();
    _memoryCache.Set(cacheKey, users, TimeSpan.FromMinutes(10));
}


Why Cache?

  • Avoids hitting the database repeatedly
  • High performance gain for read-heavy systems

Disable Change Tracking for Bulk Operations
Manual tracking causes overhead in insert/update loops.

Efficient Bulk Insert

_context.ChangeTracker.AutoDetectChangesEnabled = false;
foreach (var record in records)
{
    _context.Add(record);
}
await _context.SaveChangesAsync();
_context.ChangeTracker.AutoDetectChangesEnabled = true;


Or Use Bulk Libraries

  • EFCore.BulkExtensions
  • Dapper + BulkCopy


Best Practices Summary

  • Use AsNoTracking for read-only queries
  • Use projections to select only required columns
  • Apply pagination for large datasets
  • Avoid N+1 problems with Include
  • Let the database handle filtering
  • Use compiled queries when necessary
  • Index your database properly
  • Prefer explicit loading over lazy loading
  • Cache frequently used data
  • Use raw SQL for complex cases

Conclusion
Improving EF Core query performance is all about reducing unnecessary work—both in your code and inside the database. By applying these practical tips like AsNoTracking, pagination, projections, correct indexing, and avoiding lazy loading, you can significantly speed up your application. With the right approach, EF Core becomes both powerful and performant for building fast, scalable .NET applications.



European ASP.NET Core 10.0 Hosting - HostForLIFE :: ASP.NET Core Exception Handling

clock December 8, 2025 08:11 by author Peter

One of the most crucial components of creating reliable, safe, and production-ready apps is exception management. Errors such as faulty input, network failures, database connection problems, unhandled null values, or unauthorized access are eventually encountered by every application. The difficulty lies not in preventing these mistakes but in managing them consistently and with grace.


An extensive and potent exception-handling pipeline is offered by ASP.NET Core. Using real-world examples, global middleware, logging, structured API answers, custom exceptions, and recommended practices, this article covers exception handling from the fundamentals to sophisticated methods.

1. What is an Exception?
An exception is an unexpected event that occurs during program execution and disrupts the normal flow of the application.
Common examples include:

  • Trying to divide by zero
  • Attempting to read null values
  • Accessing invalid array indexes
  • Database connection failures
  • Invalid type conversions

Exceptions help developers identify problems, but unhandled exceptions cause application crashes. This is why exception handling is essential.

2. Why Exception Handling Is Important
Proper exception handling provides several benefits:

  • Prevents application crashes
  • Displays user-friendly messages
  • Prevents sensitive information from leaking
  • Produces reliable API responses
  • Helps developers diagnose issues through logs
  • Improves maintainability and robustness

Without exception handling, end users may see application crashes or confusing error pages. With proper handling, errors become predictable, controlled, and secure.

3. Types of Exceptions in .NET

System Exceptions
These are built-in .NET exception types, such as:

  • NullReferenceException
  • ArgumentException
  • InvalidOperationException
  • FormatException
  • IndexOutOfRangeException

Application Exceptions
Custom exceptions created by developers to handle logical or business-related issues:
public class InvalidOrderException : Exception
{
    public InvalidOrderException(string message) : base(message) { }
}

Business Rule Exceptions
These represent domain-level issues, such as:

  • Insufficient balance
  • Invalid order ID
  • Inactive account
  • Unauthorized operation

4. Try–Catch–Finally - Basic Exception Handling
The simplest form of exception handling uses try, catch, and finally blocks.
try
{
    int x = 10;
    int y = 0;
    int result = x / y;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero.");
}
catch (Exception ex)
{
    Console.WriteLine("An unexpected error occurred.");
}
finally
{
    Console.WriteLine("This block always executes.");
}


The finally block is optional and is typically used to release resources like database connections or file handles.

5. Exception Handling in ASP.NET Core
ASP.NET Core offers several layers of exception handling:

  • Developer exception page
  • Production exception handler using UseExceptionHandler
  • Custom global exception handling middleware
  • Exception filters
  • Validation responses
  • Structured error responses (Problem Details)
  • Logging via ILogger or external log providers

Each technique has a specific use case depending on whether you are in development or production.

6. Developer Exception Page - Development Environment
This provides detailed error information, including:

  • Stack trace
  • Source file and line number
  • Error message
  • Request details

Enable it only in development:
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

Never enable this in production because it exposes sensitive details.

7. Built-in Production Exception Handler - UseExceptionHandler
This middleware catches unhandled exceptions globally.

Step 1: Enable the handler in Program.cs

app.UseExceptionHandler("/error");

Step 2: Create the error endpoint
app.Map("/error", (HttpContext context) =>
{
    return Results.Problem("An unexpected error occurred.");
});


This handles all unhandled exceptions without exposing internal details.

8. Global Exception Handling Middleware - Preferred Method

Creating a custom middleware provides full control and centralizes all exception handling logic.

ExceptionMiddleware.cs
using System.Net;
using System.Text.Json;

public class ExceptionMiddleware : IMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.ContentType = "application/json";

            var errorResponse = new
            {
                StatusCode = context.Response.StatusCode,
                Message = "An unexpected error occurred.",
                Detail = ex.Message
            };

            var json = JsonSerializer.Serialize(errorResponse);
            await context.Response.WriteAsync(json);
        }
    }
}

Register in the Program.cs
builder.Services.AddTransient<ExceptionMiddleware>();
app.UseMiddleware<ExceptionMiddleware>();


This approach is suitable for production APIs.

9. Exception Filters - MVC Specific
Exception filters allow centralized handling for controller actions.

CustomExceptionFilter.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

public class CustomExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        context.Result = new JsonResult(new
        {
            Message = "An error occurred.",
            Detail = context.Exception.Message
        })
        { StatusCode = 500 };
    }
}

Register in the Program.cs
builder.Services.AddControllers(options =>
{
    options.Filters.Add<CustomExceptionFilter>();
});


Filters are useful when you want exception handling only for controllers, not for middleware-level requests.

10. Validation Exception Handling
ASP.NET Core automatically validates DTOs using data annotations.

Example DTO:
public class RegisterDto
{
    [Required]
    public string Email { get; set; }

    [MinLength(6)]
    public string Password { get; set; }
}

When validation fails, ASP.NET Core returns a structured 400 response:
{
  "errors": {
    "Password": ["The field Password must be a string with a minimum length of 6."]
  }
}

No additional exception handling is required for validation errors.

11. Structured Error Responses Using ProblemDetails
ASP.NET Core supports the Problem Details format (RFC 7807).

Example:
return Problem(
    title: "Internal Server Error",
    detail: "Database connection failed",
    statusCode: 500
);

This produces a structured response:
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Database connection failed"
}


Consistent error responses improve debugging and client-side error handling.

12. Logging Exceptions Using ILogger
Logging is critical for diagnosing issues and monitoring applications.
try
{
    int.Parse("abc");
}
catch (Exception ex)
{
    _logger.LogError(ex, "Error while parsing number");
}


Logging providers supported in ASP.NET Core:

  • Console logging
  • Debug logging
  • Serilog
  • NLog
  • Seq
  • Application Insights

Logs should be centralized in production.

13. Custom Business Exceptions
Applications often need domain-level error handling.
public class InsufficientFundsException : Exception
{
    public InsufficientFundsException(string message) : base(message) { }
}

Usage:
if (balance < amount)
    throw new InsufficientFundsException("Insufficient funds to complete transaction.");


Catch these globally and return user-friendly messages.

14. Real-World Example: Handling Exceptions in a Controller
[HttpGet("{id}")]
public async Task<IActionResult> GetOrder(int id)
{
    var order = await _context.Orders.FindAsync(id);

    if (order == null)
        throw new KeyNotFoundException("Order not found");

    return Ok(order);
}


Global middleware converts this into a structured error response without exposing sensitive details.

15. Best Practices for Exception Handling in Production

  • Never expose internal exception messages to users
  • Always log exceptions with proper context
  • Use global exception handling middleware
  • Standardize error responses with ProblemDetails
  • Use try-catch only where required
  • Validate user input before processing
  • Create custom exceptions for business logic
  • Return proper HTTP status codes
  • Separate domain, application, and infrastructure exceptions

Proper exception handling improves code quality, application reliability, and security. Thank you for reading this complete guide on Exception Handling in ASP.NET Core. Exception handling is a critical skill for building stable, secure, and maintainable applications. By implementing global handlers, logging, structured responses, and custom exception logic, you ensure your APIs remain predictable and professional under all circumstances.



European ASP.NET Core 10.0 Hosting - HostForLIFE :: Learning SqlHelper Class in .NET: ExecuteNonQuery, ExecuteDataset, ExecuteScalar

clock December 5, 2025 06:15 by author Peter

The same database tasks are frequently repeated while using Microsoft SQL Server in a.NET application:

  • Creating SQL connections
  • Making commands
  • Running queries
  • Completing DataSets
  • Giving back values

Developers make a reusable SQL Helper class to avoid repeatedly writing this boilerplate code.
Commonly used database execution techniques are provided by your SqlHelper class, including:

  • Execute Dataset
  • Run NonQuery
  • Run Scalar

Each technique is described in this article along with its rationale and useful, real-world examples.

ExecuteDataset — Fetching Records (SELECT Queries)

Purpose
To execute SELECT queries and return the result as a DataSet.

Why used?
When you need multiple tables or multiple rows

When UI needs table-like data (GridView, DataTable, Excel Export etc.)

A. ExecuteDataset (Text Query)

public DataSet ExecuteDataset(string conStr, string query)
{
    DataSet ds = new DataSet();

    using (SqlConnection con = new SqlConnection(conStr))
    {
        con.Open();
        using (SqlDataAdapter da = new SqlDataAdapter(query, con))
        {
            da.Fill(ds);
        }
    }

    return ds;
}


Real-Time Use Case
Example: Fetch IPO Master list from database and show in grid.

Example Code
SqlHelper helper = new SqlHelper();
DataSet ds = SqlHelper.ExecuteDataset(conStr, "SELECT * FROM  Userdetails");


if (ds.Tables[0].Rows.Count > 0)
{
    // Bind to Grid or dropdown
}


B. ExecuteDataset (Stored Procedure)
public static DataSet ExecuteDataset(string conStr, string proc, SqlParameter[] param, bool isSp)
{
    DataSet ds = new DataSet();

    using (SqlConnection con = new SqlConnection(conStr))
    {
        con.Open();
        using (SqlCommand cmd = new SqlCommand(proc, con))
        {
            cmd.CommandType = isSp ? CommandType.StoredProcedure : CommandType.Text;
            cmd.Parameters.AddRange(param);

            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                da.Fill(ds);
            }
        }
    }

    return ds;
}

Real-Time Use Case

When your project requires fetching data using a stored procedure with parameters.

Example: Get User details based on ID.

Example Code
SqlParameter[] param =
{
    new SqlParameter("@Id", 25)
};


DataSet ds = SqlHelper.ExecuteDataset(
    conStr,
    "sp_GetDetails",
    param,
    true
);

ExecuteNonQuery — Insert, Update, Delete (No Data Returned)
Purpose
For queries that do not return rows:

  • INSERT
  • UPDATE
  • DELETE

Stored procedures performing actions

Why used?
To know how many rows were affected.

A. ExecuteNonQuery (Stored Procedure with Parameters)
public int ExecuteNonQuery(string conStr, string proc, SqlParameter[] param, bool isSp)
{
    using (SqlConnection con = new SqlConnection(conStr))
    {
        con.Open();
        using (SqlCommand cmd = new SqlCommand(proc, con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddRange(param);

            return cmd.ExecuteNonQuery();
        }
    }
}

Real-Time Use Case
Example: Save IPO Application values (Insert).

Example Code
SqlParameter[] param =
{
    new SqlParameter("@AppNo", "12345"),
    new SqlParameter("@InvestorName", "Sandhiya")
};


SqlHelper helper = new SqlHelper();
int rows = helper.ExecuteNonQuery(
    conStr,
    "sp_InsertApplication",
    param,
    true
);

if (rows > 0)
{
    Console.WriteLine("Record Inserted Successfully!");
}


B. ExecuteNonQuery (Static)
public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText)
{
    using SqlConnection conn = new SqlConnection(connectionString);
    using SqlCommand cmd = new SqlCommand(cmdText, conn);
    cmd.CommandType = cmdType;
    conn.Open();
    return cmd.ExecuteNonQuery();
}


Real-Time Use Case
When you want a simple command without parameters.

Example
int rows = SqlHelper.ExecuteNonQuery(
    conStr,
    CommandType.Text,
    "DELETE FROM TempTable"
);


ExecuteScalar Return Single Value
Purpose
To get one single value from the database.

Used When?

  • COUNT()
  • SUM()
  • MAX()
  • MIN()
  • Get latest inserted ID

Example: Count total User records
public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText)
 {
     using SqlConnection conn = new SqlConnection(connectionString);
     using SqlCommand cmd = new SqlCommand(cmdText, conn);
     cmd.CommandType = cmdType;
     conn.Open();
     return cmd.ExecuteScalar();
 }
object count = SqlHelper.ExecuteScalar(
    conStr,
    CommandType.Text,
    "SELECT COUNT(*) FROM IPOMaster"
);


Console.WriteLine("Total IPO: " + count);

ExecuteDataset (Another Static Version)
public static DataSet ExecuteDataset(string connectionString, CommandType cmdType, string cmdText)
{
    using SqlConnection conn = new SqlConnection(connectionString);
    using SqlCommand cmd = new SqlCommand(cmdText, conn);
    cmd.CommandType = cmdType;

    using SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    return ds;
}


Purpose

Same as other ExecuteDataset but used when the developer doesn’t need parameters.

Example
DataSet ds = SqlHelper.ExecuteDataset(
    conStr,
    CommandType.Text,
    "SELECT * FROM Users"
);


Difference Between All Methods (Quick Table)

MethodPurposeReturnsUse Case
ExecuteDataset SELECT queries DataSet Fetch rows, tables
ExecuteNonQuery INSERT, UPDATE, DELETE int (affected rows) Save, update, delete data
ExecuteScalar Single value queries object COUNT(), MAX(), ID
ExecuteDataset (SP) Stored procedure results DataSet Query with parameters
ExecuteNonQuery (SP) Stored procedure actions Affected rows Insert/update using SP


About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in