Snippset

Snippset Feed

AI by Josh
...see more

Getting clear and helpful answers from ChatGPT depends a lot on how you ask your questions. By using a few simple steps, you can guide the AI to give you exactly what you need—fast and easy. 

  1. Clarify the Role:
    Start by telling ChatGPT what kind of expert or role it should take.
    Example prompt: “Please act as an experienced digital marketing consultant. I need advice to improve my social media.

  2. Explain the Situation:
    Give background information about your goal or project.
    Example prompt: “I’m preparing to launch a new product and want to find the best ways to reach my customers.

  3. Give Examples:
    Ask for sample answers or models to guide the response.
    Example prompt: “Show me three examples of Instagram posts with captions that are engaging.

  4. Choose the Tone and Style:
    Tell ChatGPT how you want the response to sound.
    Example prompt: “Use a friendly and simple tone that anyone can understand.

  5. Set the Response Format:
    Specify the length or layout you prefer.
    Example prompt: “Keep your answer under 150 words and use bullet points.

...see more

To display JSON in a structured and readable format directly in PowerShell, you can pipe a JSON string through ConvertFrom-Json and then ConvertTo-Json with an appropriate -Depth parameter. This allows you to avoid using intermediary variables and outputs neatly formatted JSON directly to the console.

Example:

'{"name":"John","age":30,"address":{"street":"123 Main St","city":"Anytown"},"phones":["123-4567","987-6543"]}' 
| ConvertFrom-Json 
| ConvertTo-Json -Depth 10

Explanation:

  • ConvertFrom-Json parses the raw JSON string into a PowerShell object.
  • ConvertTo-Json re-serializes the object with proper indentation.
  • The -Depth parameter ensures that nested objects are fully expanded in the output.

This approach is useful for quickly inspecting JSON structures without needing temporary variables or additional tools.

.NET by Jerry
...see more

When handling tokens in .NET applications, it's essential to avoid logging them in full due to the potential exposure of sensitive information. A best practice is to redact tokens before logging by showing only a prefix and/or suffix.

Here’s a robust approach:

  1. Redact tokens safely: Display only the first few and last few characters of the token, separated by ellipses (...). If the token is too short to show both, consider showing only the prefix followed by ..., or return a standardized warning.

  2. Implement a helper method: Encapsulate redaction logic in a shared utility to ensure consistent and secure usage throughout the codebase.

public static string RedactToken(string token, int prefixLength = 6, int suffixLength = 4)
{
if (string.IsNullOrEmpty(token))
return "[null or empty token]";
int minLengthForFullRedaction = prefixLength + suffixLength;
if (token.Length >= minLengthForFullRedaction)
{
var prefix = token.Substring(0, prefixLength);
var suffix = token.Substring(token.Length - suffixLength);
return $"{prefix}...{suffix}";
}
int minLengthForPrefixOnly = prefixLength + 3; // For "..."
if (token.Length >= minLengthForPrefixOnly)
{
var prefix = token.Substring(0, prefixLength);
return $"{prefix}...";
}
return "[token too short to redact securely]";
}
  1. Optional hashing for debugging: If correlation is needed without revealing the token, hash it using a secure algorithm (e.g., SHA256) and log only the hash.

By centralizing redaction in a reusable helper and applying consistent rules, applications can balance debugging needs with security best practices.

Windows by Burton
...see more

If you encounter issues with dual audio output:

  • Update Drivers: Ensure all audio drivers are current to prevent compatibility problems.
  • Check Connections: Verify that all audio devices are properly connected and recognized by the system.
  • Test Sound: Conduct sound tests to confirm audio is playing through both outputs.
  • Adjust Volume: Manage volume levels for each device to achieve balanced sound.
  • Restart System: Reboot your computer if changes do not take effect immediately.

These steps can help resolve common issues related to multiple audio outputs.

...see more

The msDS-UserPasswordExpiryTimeComputed attribute in Active Directory stores the user’s password expiration time as a large integer in Windows FileTime format. This format counts 100-nanosecond intervals from January 1, 1601 (UTC). To get a readable date and time, you must convert this number to a standard datetime format using the appropriate method for your platform.

How to Convert:

  • Use built-in functions like FromFileTimeUtc in PowerShell or .NET.
  • In Python, add the FileTime interval (converted to microseconds) to the epoch starting at 1601-01-01.

Example in PowerShell:

[DateTime]::FromFileTimeUtc($filetimeValue)

Handling the Special “Magic” Number:
If the value equals 9223372036854775807 (the maximum 64-bit integer), it is a special indicator that the password never expires. This number is not a real timestamp and should not be converted to a date. Instead, treat it as a flag meaning “no expiration.”

Summary:

  • Convert valid FileTime values to datetime for expiry information.
  • Recognize 9223372036854775807 as a sentinel meaning “password never expires.” Avoid converting this sentinel to a datetime.
...see more

This solution demonstrates how to retrieve the password expiration date of a user account in Active Directory using PowerShell. It uses the Get-ADUser cmdlet from the Active Directory module and queries the msDS-UserPasswordExpiryTimeComputed property, which holds the computed expiration date in FILETIME format.

If querying by -Identity returns an error such as "Cannot find an object with identity," switching to a -Filter approach with the SamAccountName is recommended. Also, ensure that the Active Directory module is imported, the domain context is correct, and the executing user has appropriate permissions.

# Import the Active Directory module if not already loaded
Import-Module ActiveDirectory

# Replace 'username' with the actual SamAccountName of the user
$user = Get-ADUser -Filter {SamAccountName -eq "username"} -Properties msDS-UserPasswordExpiryTimeComputed

# Convert the FILETIME to a readable DateTime object
$passwordExpiry = if ($user."msDS-UserPasswordExpiryTimeComputed") {
    [datetime]::FromFileTime($user."msDS-UserPasswordExpiryTimeComputed")
} else {
    "Password does not expire or no expiration set."
}

# Output the result
[PSCustomObject]@{
    UserName       = $user.SamAccountName
    PasswordExpiry = $passwordExpiry
}

Key Points:

  • Use -Filter with SamAccountName to avoid identity resolution issues.
  • The property msDS-UserPasswordExpiryTimeComputed returns the expiration time as FILETIME.
  • Convert FILETIME to DateTime for human-readable output.
  • Confirm the environment context and permissions to avoid access errors.
C# by Myles
...see more

When working with collections in C#, it's common to extract and concatenate specific property values for display or logging purposes. For instance, if you have a list of objects and want to join the values of a particular string property, you can use LINQ in combination with string.Join.

Scenario

You have a list of objects, each with a Name property, and you want to create a single comma-separated string of all names.

Solution

Use LINQ to project the property and string.Join to concatenate the results.

var names = string.Join(", ", items.Select(i => i.Name));

Notes

  • items is a List<T> where T has a Name property.
  • Select(i => i.Name) projects the desired property Name from each Item Item.
  • string.Join concatenates the values with a defined separator (e.g., ", " in this case).
  • To avoid nulls, you can add .Where(x => !string.IsNullOrEmpty(x.Name)).

This method is clean, efficient, and readable—ideal for transforming object data into user-friendly output or log formats.

...see more

DelegatingHandlers can be tested in isolation:

  1. Mock the Inner Handler:

    var mockHandler = new Mock<HttpMessageHandler>();
    mockHandler.Protected()
    .Setup<Task<HttpResponseMessage>>("SendAsync", ...)
    .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK));
  2. Inject into DelegatingHandler:

    var customHandler = new CustomHandler
    {
    InnerHandler = mockHandler.Object
    };
  3. Create HttpClient:

    var client = new HttpClient(customHandler);

This approach allows for unit testing the DelegatingHandler's logic without making actual HTTP calls.

...see more

This video tutorial provides a hands-on introduction to jsTree. The walkthrough covers the setup process, basic configuration, and demonstrates how to create a simple tree structure using the library. It’s aimed at developers looking for a quick start with jsTree and practical examples of how it integrates into HTML pages.

Highlights from the video:

  • Download and setup of jsTree
  • Adding a basic tree structure with static data
  • Using plugins like checkbox and search
  • Tips for integration and customization

While the video is specific to jsTree, the concepts are transferable to similar tree view libraries.

...see more

Multiple DelegatingHandlers can be chained to create a pipeline:

services.AddTransient<LoggingHandler>();
services.AddTransient<AuthenticationHandler>();
services.AddHttpClient("ChainedClient")
.AddHttpMessageHandler<LoggingHandler>()
.AddHttpMessageHandler<AuthenticationHandler>();

In this setup, LoggingHandler processes the request first, followed by AuthenticationHandler. The order of registration determines the sequence of execution.

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