Friday, April 25, 2025

Visual Studio: Disabling Add Using Statements on Paste

Of late, I am tending to paste a lot more code into existing C# source files due to AI. Visual Studio 2022 introduced a feature that after code is pasted, Visual Studio will add any missing using statements to the source file. When working with CSV-related code, without my knowledge, Visual Studio adds the following to the top of a source file:

using Microsoft.VisualBasic.FileIO;

I do not want tools such as Visual Studio 2022, Copilot, or ChatGPT to write code without my knowledge or consent.

To disable the automatic addition of using directives after pasting in Visual Studio 2022 or later:

  1. From the Tools menu, select Options…
  2. Navigate to Text Editor → C# → Advanced
  3. Uncheck Add missing using directives on paste


I have disabled this feature multiple times. It seems to re-enable. Proof of Skynet?



Visual Studio: C# Project-Level Global Usings

Visual Studio 2022 and its support for C# 10.0 and .NET 6.0 allow using statements to be placed at the project level (using the syntax global using <namespace>;), stored within the project’s Properties. To access this feature, right-click a project in Solution Explorer, select Properties from the context menu, and then choose the Global Usings tab:


Using the above cleans up individual C# files, which can become pointlessly cluttered, as shown in the following example:

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System;

It is possible to have a standalone C# file that serves the same purpose, such as a per-project GlobalUsing.cs:

global using Microsoft.AspNetCore.Http;
global using Microsoft.Extensions.Logging;
global using System.Collections.Generic;
global using System.IO;
global using System.Threading.Tasks;
global using System;

A dedicated file, such as GlobalUsing.cs, is cleaner than per-source-file using statements. However, setting project-level global usings remains the cleanest approach.

As always, beware of the following, should some malevolent entity disable the feature for your project:





Tuesday, April 1, 2025

SQL Server: T-SQL Adding a CreatedUtc and ModifiedUtc to a Database Table

As a 120 WPM typist (you read that right), ChatGPT or its cousins are a time-saver. I know the drill of adding a column or columns to an existing table. I want the columns to be required, but this means I have to first assign a value to each existing row in the database.

Take adding CreatedUtc/ModifiedUtc to a table (or all tables, long term) in a database. Here is what you tell ChatGPT:

For a SQL Server table write the following T-SQL:

  1. Use ALTER TABLE to add CreatedUtc and ModifiedUtc columns of type DATETIME2 as nullable
  2. Assign a DATETIME2 UTC value of January 1, 2025, 00:00:00 to a variable @stockCreatedDateTimeUtc
  3. Update all existing entries in the table to set CreatedUtc and ModifiedUtc to @stockCreatedDateTimeUtc
  4. Write an ALTER TABLE script to make CreatedUtc and ModifiedUtc not nullable

And here are the results but ChatGPT missed the required GO under the ALTER TABLE:

ALTER TABLE YourTableName
ADD CreatedUtc DATETIME2 NULL,
    ModifiedUtc DATETIME2 NULL;

GO

DECLARE @stockCreatedDateTimeUtc DATETIME2 = '2025-01-01 00:00:00';

UPDATE YourTableName
SET CreatedUtc = @stockCreatedDateTimeUtc,
    ModifiedUtc = @stockCreatedDateTimeUtc;

ALTER TABLE YourTableName
ALTER COLUMN CreatedUtc DATETIME2 NOT NULL;

ALTER TABLE YourTableName
ALTER COLUMN ModifiedUtc DATETIME2 NOT NULL;

Total time: under 60 seconds. Maybe 10 minutes if I typed it out by hand. You still need to know how to code T-SQL and understand SQL Server to use AI correctly.


Wednesday, November 13, 2024

PowerShell: Create a git branch for an issue (type, number and title)

 On a project the branches used take the following form where issues are of type Bug, Task, etc:

<issue type>/<user name>/<issue number>-<title>

Example branch names are:

bug/jdnarkiewicz/1234-Fix-bearer-token-authorization
task/jdnarkiewicz/6789-Add-clean-up-code-for-employee-tables

The code to create the branch name and perform a "git checkout -b" to create the branch locally is as follows (script New-Branch.ps1):

param(
    [Parameter(Mandatory=$true)]
    [string] $issueType,
    [Parameter(Mandatory=$true)]
    [string] $issueNumber,
    [Parameter(Mandatory=$true)]
    [string] $issueTitle
)

Set-StrictMode -Version 3.0
$ErrorActionPreference = 'Stop'
Set-PSDebug -Off
# Set-PSDebug -Trace 1

[int] $exitCodeSuccess = 0

[int] $exitCodeError = 1

[int] $exitCode = $exitCodeSuccess

function Get-UserNameCore {
    [string] $userName = (whoami)
    [int] $lastBackslashIndex = $userName.LastIndexOf('\')

    if ($lastBackslashIndex -ge 0) {
        $userName = $userName.Substring($lastBackslashIndex + 1)
    }

    return $userName
}

function Get-BranchCore {
    param(
        [Parameter(Mandatory=$true)]
        [string] $issueTitle
    )

    return ($issueTitle -replace '[ ,./:\\=]', '-').Trim()
}

try {
    [string] $userName = Get-UserNameCore
    [string] $branchBody = Get-BranchCore $issueTitle
    [string] $branchName = "$issueType/$userName/$issueNumber-$branchBody"

    $gitResult = git checkout -b $branchName 2>&1
    if ($LASTEXITCODE -ne 0) {
        throw "Failed to create branch: $branchName. Error: $gitResult"
    }
    
    Write-Host "Created: $branchName"
}

catch {
    [System.Management.Automation.ErrorRecord] $errorRecord = $PSItem

    $exitCode = $exitCodeError
    Write-Host $errorRecord
    Write-Host `
        "Exception Message: $($errorRecord.Exception.Message), " + `
        "Line: $($errorRecord.InvocationInfo.ScriptLineNumber), " + `
        "Stacktrace: $($errorRecord.Exception.StackTrace)"
}

return $exitCode

The corresponding launch.json is follows:


{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "New-Branch",
            "type": "PowerShell",
            "request": "launch",
            "script": "${workspaceRoot}\\New-Branch.ps1",
            "args": [
                "-issueType", "bug",
                "-issueNumber", "1234",
                "-issueTitle", "'Clean up code formatting'"
            ]
        }
    ]
}






Git: Merging a branch and Prioritizing Current Branch

In a local git repo, I was working on a branch. I had to merge with main. During the merge I wanted the changes made in my branch to be prioritized over any changes in main. On some projects, I'm just an arrogant sod that way.

This is the git command that merged branch, main, with my current branch and prioritizes the. current branch with the merge:

git merge -s ours main

The result of the following command will be to:

  • Ignores all changes from branch, main.
  • Keeps all the changes from the current branch which means any changes made to the main branch will be discarded.

Thursday, August 1, 2024

Windows 11: Remove Microsoft News Widget

I will not make negative comments in my blog. Here is the command to uninstall the Microsoft News widget on Windows 11:

winget uninstall MicrosoftWindows.Client.WebExperience_cw5n1h2txyewy 



Sunday, July 28, 2024

Git: get remote URL of local Git Repo

From a console window where the current folder corresponds to a local git repo, run the following from a console:

git remote -v

An example output from this command is as follows:

origin  https://softwarepronto.visualstudio.com/Blog/_git/Scratch (push)