Snippset

Snippset Feed

...see more

When creating API endpoints in ASP.NET Core, you often need to ensure only authenticated users can access certain actions.
The [Authorize] attribute makes this easy — it automatically blocks unauthenticated requests.

Sometimes, you also load the current user from a database or a user service. In this case, it’s a good practice to add a null check as an extra safety step, even if [Authorize] is already applied.

Example

[Authorize]
[HttpPost("DoSomething")]
public async Task<IActionResult> DoSomething(RequestModel request)
{
    var user = await userService.GetContextUserAsync();

    if (user == null)
    {
        // Safety check in case the user is authenticated but not found in the database
        return Unauthorized("User not found.");
    }

    // Continue with the action
    return Ok("Action completed successfully.");
}

Key Ideas

  • [Authorize] ensures only authenticated users reach your action.
  • If your app looks up users in a database, add an extra if (user == null) check.
  • This prevents errors when tokens are valid but the user record no longer exists.

This pattern keeps your API safe, clean, and reliable.

React by Riley
...see more

When building forms in React, sometimes you want one field to copy values from another field — but only if it is still empty. For example, you may want a mediaContentUrl field to auto-fill with the same value a user types in another field.

A common problem is that after the first letter, the mediaContentUrl field is no longer "empty," so it stops updating. The trick is to keep syncing while it matches the other field, and stop once the user edits it directly.

Here’s a simplified fix you can use inside your change handler:

setFormValues(prev => {
  const updated = { ...prev, [name]: value, mediaFile: null };

  // Only sync if mediaContentUrl is empty
  // or still the same as the field being typed
  if (name !== "mediaContentUrl") {
    const prevField = String(prev[name] ?? "");
    const prevMedia = String(prev.mediaContentUrl ?? "");
    if (!prevMedia || prevMedia === prevField) {
      updated.mediaContentUrl = value;
    }
  }

  return updated;
});

This way, the mediaContentUrl field will auto-fill until the user changes it, and then it stops syncing.

.NET by Jerry
...see more

In .NET applications, it’s common to have multiple classes that share the same interface or base class. Instead of registering each class manually in the Dependency Injection (DI) container, you can register them all automatically by scanning the assembly.

Here’s a simple example:

var serviceTypes = typeof(IServiceBase)
    .Assembly
    .GetTypes()
    .Where(t =>
        typeof(IServiceBase).IsAssignableFrom(t) &&
        !t.IsAbstract &&
        !t.IsInterface);

foreach (var type in serviceTypes)
{
    services.AddSingleton(typeof(IServiceBase), type);
}

// If you also need a concrete type directly
services.AddSingleton<SpecialService>();

// Example: register a factory or manager
services.AddSingleton<IServiceFactory, ServiceFactory>();

This pattern ensures:

  • All implementations of IServiceBase are available through IEnumerable<IServiceBase>.
  • Specific concrete classes can still be injected directly when needed.
  • The system automatically picks up new implementations without changing the registration code.
.NET by Jerry
...see more

When registering services, you must decide how long they should live in your application:

  • Singleton: One instance for the entire application. Best for stateless or shared services.
  • Scoped: One instance per request or operation. Best for services tied to a unit of work.
  • Transient: A new instance every time it’s requested. Best for lightweight and short-lived services.

General advice:

  • Use Singleton if the service is stateless or used in background tasks.
  • Use Scoped if it relies on request-specific data (like database contexts).
  • Use Transient if it should always be fresh and independent.

Choosing the right lifetime prevents resource leaks, avoids threading issues, and makes your application more reliable.

C# by Myles
...see more

How to Convert Dictionary Keys into a Comma-Separated String in C#

When working with a Dictionary<string, object> in C#, you may need to get all the keys as a single string. This can be done easily using the built-in string.Join method.

Here’s a simple example:

var dict = new Dictionary<string, object>
{
    { "Name", "Alice" },
    { "Age", 30 },
    { "Country", "USA" }
};

string keys = string.Join(",", dict.Keys);
Console.WriteLine(keys); // Output: Name,Age,Country
  • dict.Keys gives you the collection of keys
  • string.Join combines them with commas

This approach is clean, fast, and works well for logging, debugging, or exporting keys.

...see more

If you're upgrading your home internet, Wi-Fi 7 mesh systems promise blazing speeds, lower latency, and better performance in busy, device-packed households. This video breaks down the top 5 options available now, balancing speed, coverage, and value.

Highlights:

  • Budget Pick: TP-Link Deco BE63 — Affordable and fast enough for 4K/8K streaming and gaming. Ideal for smaller homes.
  • Power Users: ASUS ZenWiFi BQ16 Pro — Advanced features, strong security, and deep customization for tech-savvy users.
  • Smart Home Friendly: Amazon Eero Max 7 — Great for Alexa-based homes with built-in Matter/Thread support and easy voice control.
  • Best Value: TP-Link Deco BE85 — High-performance, quad-band Wi-Fi 7 with simple setup and strong security.
  • Top Performer: Netgear Orbi RBE973 — Premium build, ultra-fast speeds (up to 27 Gbps), and elite performance for large homes.

Whether you're streaming, gaming, or building a smart home, there’s a system on this list that fits your needs and budget.

Watch the full breakdown on YouTube

Windows by Burton
...see more

If the built-in Stereo Mix method is unavailable or insufficient:

  • VoiceMeeter: A third-party application that provides advanced audio routing capabilities, allowing for complex configurations of multiple audio outputs.
  • Audio Splitters: Physical devices that can duplicate audio signals to multiple outputs without software configuration.

These alternatives offer additional flexibility for managing multiple audio outputs.

...see more

Wi-Fi 7 mesh systems are the next big thing in home networking, offering ultra-fast speeds, better range, and improved connectivity for demanding households. This comparison breaks down five top contenders: TP-Link Deco BE85 & BE95, ASUS BQ16 Pro, Eero Max 7, and Netgear Orbi 970.

  • Best Overall for Wireless Backhaul: TP-Link Deco BE95 delivered the fastest speeds without cables, ideal for homes where wiring is limited.
  • Most Advanced Configuration: ASUS BQ16 Pro shines with a rich feature set, great performance, and no extra subscriptions — perfect for tech enthusiasts.
  • Fastest Wi-Fi Speeds: Eero Max 7 surprised with top wireless speeds, especially in close-range tests.
  • Best Long-Range Performance: Netgear Orbi 970 stood out in 100-foot range tests, maintaining strong and stable performance.
  • Value Pick: TP-Link BE85 offers nearly identical features to the BE95 at a lower cost.

Each system supports up to 10Gbps speeds and offers mobile apps for setup. However, ASUS stands out with advanced settings and no added fees for features like parental controls or security.

Watch the full video comparison on YouTube

.NET by Jerry
...see more

When building background services in .NET, it’s helpful to include structured logging for better traceability and diagnostics. One common pattern is using logging scopes to include context like the service or task name in each log entry.

Instead of manually providing this context everywhere, you can simplify the process by automatically extracting it based on the class and namespace — making the code cleaner and easier to maintain.


✅ Goal

Replace this verbose pattern:

_logger.BeginScope(LoggingScopeHelper.CreateScope("FeatureName", "WorkerName"));

With a simple, reusable version:

_logger.BeginWorkerScope();

Implementation

🔧 1. Logger Extension

public static class LoggerExtensions
{
    public static IDisposable BeginWorkerScope(this ILogger logger)
    {
        var scopeData = LoggingScopeHelper.CreateScope();
        return logger.BeginScope(scopeData);
    }
}

🧠 2. Logging Scope Helper

public static class LoggingScopeHelper
{
    public static Dictionary<string, object> CreateScope()
    {
        var stackTrace = new System.Diagnostics.StackTrace();
        var frames = stackTrace.GetFrames();

        string featureName = "Unknown";
        string workerName = "Unknown";

        foreach (var frame in frames ?? Array.Empty<StackFrame>())
        {
            var method = frame.GetMethod();
            var type = method?.DeclaringType;

            if (type == null || type.Name.StartsWith("<") || type.Namespace?.StartsWith("System") == true)
                continue;

            workerName = type.Name;

            var ns = type.Namespace;
            var segments = ns?.Split('.');
            if (segments?.Length >= 3)
            {
                featureName = segments[2]; // Assuming format: Company.App.Feature.Workers
            }

            break;
        }

        return new Dictionary<string, object>
        {
            ["Feature"] = featureName,
            ["Worker"] = workerName
        };
    }
}

Example Usage in a Worker

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    using (_logger.BeginWorkerScope())
    {
        // Your background task logic
    }
}

This ensures that every log written within the scope will automatically include "Feature" and "Worker" values, without manually specifying them.

...see more

Sometimes configuration files or scripts include identifiers that need to be updated automatically — for example, replacing a generic keyword like "rule-template" with a dynamic name based on a service or environment.

This Snipp shows how to:

  • Replace an exact identifier in a file
  • Normalize that name (e.g. replacing special characters like dots)

Goal

Replace this:

rule-template

With something like:

rule-example-service

Where "example.service" is the dynamic input.

PowerShell Example

# Define the original dynamic name
$name = "example.service"

# Normalize the name (e.g., replace '.' with '-')
$normalizedName = $name -replace '\.', '-'

# Read the text file content
$content = Get-Content -Path "file.txt" -Raw

# Replace the exact identifier
$content = $content -replace 'rule-template', "rule-$normalizedName"

# Save the updated content
Set-Content -Path "file.txt" -Value $content

This ensures that:

  • Only exact matches of "rule-template" are replaced
  • Any special characters in the name are safely converted

Summary

This method is useful when working with reusable config files across different services or environments. PowerShell makes it easy to normalize and apply names consistently, reducing manual edits and potential mistakes.

Add to Set
  • .NET
  • Agile
  • AI
  • ASP.NET Core
  • Azure
  • C#
  • Cloud Computing
  • CSS
  • EF Core
  • HTML
  • JavaScript
  • Microsoft Entra
  • PowerShell
  • Quotes
  • React
  • Security
  • Software Development
  • SQL References
  • Technologies
  • Testing
  • Visual Studio
  • Windows