question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Consuming Npgsql inside PowerShell 5.1

See original GitHub issue

The issue

I am trying to consume the npgsql package with PowerShell 5.1. I tried out three versions:

  • 5.0.3
  • 4.1.8
  • 4.0.11 Only 4.0.11 seems to work.

Steps to reproduce

4.0.11: Add-Type -Path “npgsql.dll” This works.

4.1.8: Add-Type -Path “npgsql.dll” results in add-type : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more informati on.

try {
Add-Type -Path "npgsql.dll"
}
catch {
$err = $_
}

$err.Exception.LoaderExceptions

yields:

Could not load file or assembly 'System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc
7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.

5.0.3: Also yields

Could not load file or assembly 'System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc
7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.

I fiddled with additional Add-Type and also provided the -ReferencedAssemblies parameter but to no avail.

Further technical details

Operating system: Windows 10

Other details about my project setup: PowerShell 5.1

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:8 (6 by maintainers)

github_iconTop GitHub Comments

3reactions
Brarcommented, Mar 22, 2021

Just out of curiosity I tried how Npgsql would work from a current PowerShell and got the following example to run:

# PowerShell 7.1.3 on Windows connecting to a local database using integrated security
New-Item -Name "NpgsqlExample" -ItemType "directory"
Set-Location -Path "NpgsqlExample"
Install-Package -Name Npgsql -ProviderName NuGet -Scope CurrentUser -RequiredVersion 5.0.3 -SkipDependencies -Destination . -Force
$NpgsqlPath = Resolve-Path ".\Npgsql.5.0.3\lib\netstandard2.1\Npgsql.dll"
[System.Reflection.Assembly]::LoadFrom($NpgsqlPath)
try
{
    $conn = [Npgsql.NpgsqlConnection]::new("Host=localhost;Username=$Env:USERNAME;Integrated Security=true")
    $conn.Open()
    $cmd = [Npgsql.NpgsqlCommand]::new("CREATE TABLE data (id integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY, value text NOT NULL)", $conn)
    $cmd.ExecuteNonQuery()
    $cmd.CommandText = "INSERT INTO data (value) VALUES ('First row'), ('Second row'), ('Third row')"
    $cmd.ExecuteNonQuery()
    $cmd.CommandText = "SELECT value FROM data"
    $reader = $cmd.ExecuteReader()
    while($reader.Read())
    {
        Write-Host $reader.GetString(0)
    }
}
finally
{
    if ($null -ne $reader)
    {
        $reader.Dispose()
        $reader = $null
    }
    if ($null -ne $cmd)
    {
        $cmd.Dispose()
        $cmd = $null
    }
    if ($null -ne $conn)
    {
        $conn.Dispose()
        $conn = $null
    }
}

0reactions
Brarcommented, May 16, 2022

Hi @KrisztianKaszas, my example above also works on PowerShell 5.1.x but you have to be aware of the fact that the “classic” PowerShell versions rely on .NET Framewok (4.5 to be precise). This is why Npgsql 4.0.x is the latest version you can use. Also since Npgsql for .NET framework needs a few NuGet packages to work you have to make sure that they are also available and resolved in the appropriate way. This makes my example a bit longer but it should still work.

# PowerShell 5.1.19041.1682 on Windows connecting to a local database using integrated security
# You may need to install the NuGet package provider via Install-PackageProvider -Name "NuGet"
New-Item -Name "NpgsqlExample" -ItemType "directory"
Set-Location -Path "NpgsqlExample"

Install-Package -Name System.Threading.Tasks.Extensions -ProviderName NuGet -Scope CurrentUser -RequiredVersion 4.5.4 -SkipDependencies -Destination . -Force
Install-Package -Name System.Runtime.CompilerServices.Unsafe -ProviderName NuGet -Scope CurrentUser -RequiredVersion 5.0.0 -SkipDependencies -Destination . -Force
Install-Package -Name System.Memory -ProviderName NuGet -Scope CurrentUser -RequiredVersion 4.5.4 -SkipDependencies -Destination . -Force
Install-Package -Name Npgsql -ProviderName NuGet -Scope CurrentUser -RequiredVersion 4.0.12 -SkipDependencies -Destination . -Force

$npgsqlPath = Resolve-Path ".\Npgsql.4.0.12\lib\net45\Npgsql.dll"
$taskExtensionsPath = Resolve-Path ".\System.Threading.Tasks.Extensions.4.5.4\lib\netstandard1.0\System.Threading.Tasks.Extensions.dll"
$compilerServicesUnsafePath = Resolve-Path ".\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll"
$systemMemoryPath = Resolve-Path ".\System.Memory.4.5.4\lib\netstandard1.1\System.Memory.dll"

$onAssemblyResolve = [System.ResolveEventHandler] {
param($sender, $e)

Write-Verbose "Resolving '$($e.Name)'"
if ($e.Name -like 'System.Threading.Tasks.Extensions, *') {
    return [System.Reflection.Assembly]::LoadFrom($taskExtensionsPath)
}
elseif ($e.Name -like 'System.Runtime.CompilerServices.Unsafe, *') {
    return [System.Reflection.Assembly]::LoadFrom($compilerServicesUnsafePath)
}
elseif ($e.Name -like 'System.Memory, *') {
    return [System.Reflection.Assembly]::LoadFrom($systemMemoryPath)
}

Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
return $null
}
[System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
[System.Reflection.Assembly]::LoadFrom($npgsqlPath)

try
{
    $conn = [Npgsql.NpgsqlConnection]::new("Host=localhost;Username=$Env:USERNAME;Integrated Security=true")
    $conn.Open()
    $cmd = [Npgsql.NpgsqlCommand]::new("CREATE TABLE data (id integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY, value text NOT NULL)", $conn)
    $cmd.ExecuteNonQuery()
    $cmd.CommandText = "INSERT INTO data (value) VALUES ('First row'), ('Second row'), ('Third row')"
    $cmd.ExecuteNonQuery()
    $cmd.CommandText = "SELECT value FROM data"
    $reader = $cmd.ExecuteReader()
    while($reader.Read())
    {
        Write-Host $reader.GetString(0)
    }
}
finally
{
    if ($null -ne $reader)
    {
        $reader.Dispose()
        $reader = $null
    }
    if ($null -ne $cmd)
    {
        $cmd.Dispose()
        $cmd = $null
    }
    if ($null -ne $conn)
    {
        $conn.Dispose()
        $conn = $null
    }
}

[System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)

Full disclosure: After successfully executing the above code I sometimes run into a StackOverflowException terminating my PowerShell process when I keep executing commands afterwards. I’m not sure if/how it is related as it happens completely independent of my script execution but it is at least a weird coincidence. Edit: It turns out that it was the custom ResolveEventHandler that caused the crashes (executing the script in pwsh which didn’t crash gave me the hint). I’ve updated the script to unregister the handler after the assemblies have been resolved.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using npgsql via powershell 5.1 with .net 4.x
Using npgsql via powershell 5.1 with .net 4.x. ... After loading npgsql.dll the others will be loaded in lazy mode automatically. The connection...
Read more >
How to import the npgsql module? - postgresql
Download Npgsql-3.0.5.msi from the npgsql website and run the installer · Search for a DLL named 'Npgsql.ll' · Copy this dll to your...
Read more >
Powershell and Postgres – improving INSERT performance
I have a postgres database which I populate via a powershell script. I'm having trouble with the time it takes to for the...
Read more >
ODBC Calling Fill - Unexptected closed connection after 2 hours
I have a query that is executed through an ODBC connection in a Powershell 5.1 script. I use the Fill() method to retreive...
Read more >
Provisioning Azure SQL database using Azure PowerShell
This article will show how to create an Azure SQL database using Azure PowerShell.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found