Snippset

Snippset Feed

...see more

Retrieving data from a URL or calling a web API is one of the most common PowerShell tasks. Whether you want to check a website’s status, download a file, or interact with a REST API, PowerShell provides built-in commands for this purpose.

1. Using Invoke-WebRequest

Invoke-WebRequest is used to fetch web pages or files.
Example:

$response = Invoke-WebRequest -Uri "https://example.com"
$response.Content

This command returns the full HTTP response, including status code, headers, and body content.

To download a file:

Invoke-WebRequest -Uri "https://example.com/file.zip" -OutFile "C:\Temp\file.zip"

2. Calling APIs with Invoke-RestMethod

For APIs that return JSON or XML, Invoke-RestMethod is the better choice. It automatically converts the response into PowerShell objects:

$data = Invoke-RestMethod -Uri "https://api.github.com"
$data.current_user_url

You can also send POST requests:

Invoke-RestMethod -Uri "https://api.example.com/data" -Method POST -Body '{"name":"John"}' -ContentType "application/json"

3. Running PowerShell from the Command Line

PowerShell commands can be executed directly from the traditional Windows Command Prompt:

powershell -Command "Invoke-WebRequest -Uri 'https://example.com'"

Or, if available, using curl:

curl https://example.com

Summary

With just a few commands, PowerShell becomes a versatile tool for web requests and API communication — ideal for automation, system monitoring, or accessing online data sources.

Azure by Martin
...see more

When an IP address no longer requires access, delete its firewall rule to maintain a secure environment.

Delete a server-level rule:

EXECUTE sp_delete_firewall_rule @name = 'AllowOfficeIP';

Delete a database-level rule:

EXECUTE sp_delete_database_firewall_rule @name = 'AllowDevMachine';

If you encounter issues deleting rules (for instance, due to missing permissions), ensure you’re connected with sufficient administrative rights or use the Azure Portal for manual removal.

Source: Microsoft Docs – sp_delete_database_firewall_rule

Azure by Martin
...see more

To check which IP addresses have access to your Azure SQL Database, use the following T-SQL queries:

To list server-level firewall rules:

SELECT * FROM sys.firewall_rules;

To list database-level firewall rules:

SELECT * FROM sys.database_firewall_rules;

This helps verify which IP ranges currently have access and ensures that no outdated or overly broad rules are active. Regular audits of firewall rules are essential for maintaining data security.

Source: Todd Kitta GitHub – Configure Firewall Settings T-SQL

Azure by Martin
...see more

You can create firewall rules in Azure SQL using T-SQL commands or directly in the Azure Portal.

Using T-SQL (Server-level example):

EXECUTE sp_set_firewall_rule 
    @name = 'AllowOfficeIP', 
    @start_ip_address = '203.0.113.0', 
    @end_ip_address = '203.0.113.0';

For a database-level rule:

EXECUTE sp_set_database_firewall_rule 
    @name = 'AllowDevMachine', 
    @start_ip_address = '198.51.100.10', 
    @end_ip_address = '198.51.100.10';

Tip: Always double-check the IP range and limit access to only the addresses that genuinely need it to avoid overly broad access.

Source: SQLShack – Configure IP Firewall Rules for Azure SQL Databases

Azure by Martin
...see more

Azure SQL uses a layered firewall model:

  • Server-level firewall rules: These define allowed IP address ranges for the entire logical SQL server. Any database under that server inherits these settings.
  • Database-level firewall rules: These are stored within an individual database and apply only to connections to that database.

When to use each:

  • Use server-level rules when multiple databases need the same IP access.
  • Use database-level rules when access needs to be restricted to specific databases or when users lack server-level permissions.

Example:

  • Allowing your organization’s office IP to access all databases? → Use server-level.
  • Granting temporary access to a consultant for one database? → Use database-level.

Reference: Rishan Digital – Firewall Rules and Authentication

Azure by Martin
...see more

Firewall rules in Azure SQL Database control which IP addresses can connect to your database server. Configuring these rules correctly ensures that only trusted users and applications access your data while keeping it secure from unauthorized traffic.

Azure provides two levels of firewall configuration: server-level and database-level rules. Server-level rules allow access to all databases under a logical server, while database-level rules apply only to a specific database.

You can configure firewall rules using the Azure Portal, Transact-SQL (T-SQL) commands, or PowerShell. Understanding how and where to apply these rules helps ensure a secure and flexible environment for managing database access.

Learn more from Microsoft Docs

...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.

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
  • Technology
  • Testing
  • Visual Studio
  • Windows
Actions