New-Object : Exception calling ".ctor" with "0" argument(s): "The type initializer for 'MimeKit.ParserOptions' threw an exception." - circular-dependency

Background:
Trying to send an email with Powershell on Win10, and wanting to communicate with an SMTP server using port 587 and TLS 1.2.
Trying to use the Nuget Gallery packages: MailKit and its dependency MimeKit because Microsoft does not recommend System.Net.Mail.SmtpClient given security concerns.
Used Powershell Install-Package cmdlet to install the MailKit (this seemed to work) and then same for the MimeKit, but the MimeKit package installation failed (and as you can see the exception string is not particularly helpful as to the exact nature of the dependency loop):
PS C:\bin\ps1\renew_certs> Install-Package -Name 'MimeKit' -Source "https://www.nuget.org/api/v2" -Force
Install-Package : Dependency loop detected for package 'MimeKit'.
At line:1 char:1
+ Install-Package -Name 'MimeKit' -Source "https://www.nuget.org/api/v2 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : Deadlock detected: (MimeKit:String) [Install-Package], Exception
+ FullyQualifiedErrorId :
DependencyLoopDetected,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage
PS C:\bin\ps1\renew_certs> ($error[0].Exception.GetBaseException())
Dependency loop detected for package 'MimeKit'.
Another answer here about dependency loop exceptions suggested to use the -SkipDependency parameter on Install-Package cmdlet, and this avoided the installation exception.
I moved on to try to run my code however this resulted in an exception (very similar to the exception to this one this question is about) and in that case
PS C:\bin\ps1\renew_certs> ($error[0].Exception.GetBaseException())
result string indicated the file or assembly that could not be loaded was the package Portable.BouncyCastle which is identified as a dependency of the MimeKit.
So, I used Install-Package for Portable.BouncyCastle (I did not use -SkipDependencies so I assume they installed), and then in the code used Add-Type to load the DLL too.
This seemed to prevent the BouncyCastle related exception; however, running the code now yields the exception that is the topic of my question:
Code:
Add-Type -Path "C:\Program Files\PackageManagement\NuGet\Packages\System.Text.Encoding.CodePages.6.0.0\lib\netstandard2.0\System.Text.Encoding.CodePages.dll"
Add-Type -Path "C:\Program Files\PackageManagement\NuGet\Packages\Portable.BouncyCastle.1.9.0\lib\netstandard2.0\BouncyCastle.Crypto.dll"
Add-Type -Path "C:\Program Files\PackageManagement\NuGet\Packages\MimeKit.3.3.0\lib\netstandard2.0\MimeKit.dll"
Add-Type -Path "C:\Program Files\PackageManagement\NuGet\Packages\MailKit.3.3.0\lib\netstandard2.0\MailKit.dll"
$SMTP = New-Object MailKit.Net.Smtp.SmtpClient
$Message = New-Object MimeKit.MimeMessage
<#
$TextPart = [MimeKit.TextPart]::new("plain")
$TextPart.Text = "There was a deployment"
<#
Exception:
PS C:\bin\ps1\renew_certs> . "c:\bin\ps1\renew_certs\send_email.ps1"
New-Object : Exception calling ".ctor" with "0" argument(s): "The type initializer for 'MimeKit.ParserOptions' threw an exception."
At C:\bin\ps1\renew_certs\send_email.ps1:9 char:13
+ $Message = New-Object MimeKit.MimeMessage
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
PS C:\bin\ps1\renew_certs> ($error[0].Exception.GetBaseException())
Could not load file or assembly 'System.Text.Encoding.CodePages, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its
dependencies. The system cannot find the file specified.
PS C:\bin\ps1\renew_certs>
The System.Text.Encoding.CodePages is listed as a dependency of the MimeKit, so I tried to resolve similar to the BouncyCastle case, but System.Text.Encoding.CodePages install fails with a dependency loop too. So, I did install with -SkipDependencies flag, and explicitly add DLL with Add-Type in my code; however, still the same exception.
The dependency noted at MimeKit for System.Text.Encoding.CodePages says (>= 4.5.1) and the one installed was System.Text.Encoding.CodePages.6.0.0 directory. The exception error string says file or assembly that could not be loaded was Version=4.1.1.0, but I don't see any 4.1.* versions at the gallery.
Wondering if it was a dependency of System.Text.Encoding.CodePages, I then tried to install the System.Memory package but it also failed on a dependency loop error, and looking at its dependencies tab I was overwhelmed.
Is there any way to see a trace of exactly why the dependency loop errors are occurring, or what files are actually missing?
Is the issue perhaps something else entirely?
The exception string says "The system cannot find the file specified." Is there anyway to see the exact filepath that is not found?
When I ran the Powershell debugger in VS Code the exception is thrown stepping into [MimeKit.TextPart]::new("plain"). Anyway to debug down into the DLL?

You need exactly System.Text.Encoding.CodePages v4.5.1 (6.0.0 broke compatibility).
You may still have errors because you used -SkipDependencies so who knows what all you are still missing.

Related

Persistent error with Newtonsoft.Json.JsonReaderException

I have been attempting to run commands from the AzureAD powershell module, but I am consistently getting Json errors.
The issue is so persistent no matter what commands I run, I am wondering if the Newtonsoft.Json package is misconfigured and needs to be reinstalled.
Example:
New-AzureADServiceAppRoleAssignment -Id "any id" -ResourceId "any id" -ObjectId "any id" -PrincipalID "any id"
Output:
Error reading JToken from JsonReader. Path '', line 0, position 0
At line:1 char:1
New-AzureADServiceAppRoleAssignment -Id ....
CategoryInfo : NotSpecified: (:) [New-AzureADServiceAppRoleAssignment], JsonReaderException
FullyQualifiedErrorId: Newtonsoft.Json.JsonReaderException.Microsoft.Open.AzureAD16.Powershell.NewServicePrincipalAppRoleAssignment.
I tried in my environment and got successfully created a new app role service principal assignments:
Commands:
Connect-AzureAD
New-AzureADServiceAppRoleAssignment -ObjectId $servicePrincipal.ObjectId -PrincipalId $servicePrincipal.ObjectId -ResourceId $resourceApp.ObjectId -Id $permission.Id
Console:
Portal:
Make sure you are using latest version of Newtonsoft.json.
if you are using lower version, try to uninstall and reinstall the latest version by below command:
Install-Module -Name newtonsoft.json -RequiredVersion 1.0.1.2
If the error is still persisting uninstall AzureAD module reinstall the AzureAD-Module confirm all the traffic can be passed the network policy (Firewall) .
Verify if you are using the latest version of Azure AD PowerShell module? Also, validate if your local machine's firewall is restricting the command? Or if you're connected to any VPN or organizational laptop.
If AzureAD module is already installed, Install new version(2.0.2.140).
Command:
Install-Module -Name AzureAD --Allowclobber
Reference:
Getting error when running script · Issue #2 · adrecon/AzureADRecon (github.com)

not working Install-Package Microsoft.SqlServer.Types

I am trying to deploy an SSRS report that is made on Microsoft SQL Server Builder Report
but I get this error:
System.Web.Services.Protocols.SoapException: An unexpected error
occurred in Report Processing. --->
Microsoft.ReportingServices.ReportProcessing.ReportProcessingException:
An unexpected error occurred in Report Processing. --->
System.IO.FileNotFoundException: Could not load file or assembly
'Microsoft.SqlServer.Types, Version=14.0.0.0, Culture=neutral,
PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The
system cannot find the file specified. at
Microsoft.ReportingServices.Library.ReportingService2010Impl.CreateReportEditSession(String
Report, String Parent, Byte[] Definition, String& EditSessionID,
Warning[]& Warnings) at
Microsoft.ReportingServices.WebServer.ReportingService2010.CreateReportEditSession(String
Report, String Parent, Byte[] Definition, String& EditSessionID,
Warning[]& Warnings)
Somewhere I found to install Microsoft.SqlServer.Types. The thing is how do I do this in this program.
It says to install Microsoft.SqlServer.Types. So thinking of other possibilities I tried to install it in Visual Studio because I know you can also make a report through visual studio. I made my project and it also got a mistake so I thought it is the same error. Therefore I tried to run
PM> Install-Package Microsoft.SqlServer.Types
Install-Package : Project 'Default' is not found. At line:1 char:1
+ Install-Package Microsoft.SqlServer.Types
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Default:String) [Install-Package], ItemNotFoundException
+ FullyQualifiedErrorId : NuGetProjectNotFound,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
and again I got a mistake. I have NuGet install

Error 0x80131047 loading MySQL Connector DLL

PowerShell has just been opened sourced (v6.0.0-alpha.10), and I'm
trying to get it to connect to a MySQL instance from OS X.
Oracle seems to suggest (if I'm reading it correctly) that they have a
.Net Core connector
here.
I ran the install like this:
Install-Package MySql.ConnectorNET.Entity -Destination /MySQL
and the output looked good:
Name Version Source Summary
---- ------- ------ -------
MySql.ConnectorNET.Data 6.8.3.2 nugget ADO.Net driver for MySQL
MySql.ConnectorNET.Entity 6.8.3.2 nugget MySql Connector/NET for Entity Framework 6
When I try loading the assembly like this:
[System.Reflection.Assembly]::Load(/MySQL/MySql.ConnectorNET.Data.6.8.3.2/lib/net45/MySql.Data.dll)
I get the following error (note that I pass the path in with a
variable $dll):
Exception calling "Load" with "1" argument(s): "Could not load
file or assembly
'/MySQL/MySql.ConnectorNET.Entity.6.8.3.2/lib/net40/MySql.Data.dll,
Culture=neutral, PublicKeyToken=null'. The given assembly name or
codebase was invalid. (Exception from HRESULT: 0x80131047)" At
/development/scripts/test.ps1:28 char:1
+ [System.Reflection.Assembly]::Load("$dll")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileLoadException
Any ideas on a workaround / fix? I realize that PowerShell is still in
alpha.
EDIT
I was able to install the MySQL provider using these two commands:
Register-PackageSource -Name nuget.org -ProviderName NuGet -Location https://www.nuget.org/api/v2/
Install-Package MySql.Data.EntityFrameworkCore -Destination /Volumes/Main/libraries/MySQL/ -AllowPrereleaseVersions
I tried registering all the assemblies I could think of:
Microsoft.EntityFrameworkCore.1.0.1/lib/netstandard1.3/Microsoft.EntityFrameworkCore.dll
Microsoft.Extensions.Configuration.1.0.0/lib/netstandard1.1/Microsoft.Extensions.Configuration.dll
Microsoft.Extensions.Configuration.Json.1.0.0/lib/netstandard1.3/Microsoft.Extensions.Configuration.Json.dll
MySql.Data.EntityFrameworkCore.7.0.5-IR21/lib/netstandard1.6/MySql.Data.EntityFrameworkCore.dll
MySql.Data.7.0.5-IR21/lib/netstandard1.6/MySql.Data.dll
But, when trying to create a new MySql object, it still bombs out with
this:
New-Object : Cannot find type [MySql.Data.MySqlClient]:
verify that the assembly containing this type is loaded.
That is not a .NET Core library - the word "Core" here indicates functionality shared between the EF6 and Web packages, and pre-dates the introduction of .NET Core.
Entity Framework Core has MySql libraries under development at the time of writing.
SOLUTION
So, it turns out I was on the (mostly) right track. All of the DLLs need to be loaded. Make life easier by copying them into their own directory, and then load them by iterating over each one:
copy the DLLs to a new location
Get-ChildItem "/Volumes/Main/libraries/mysql/*/lib/netstandard1.*/*.dll" | Copy-Item -Destination "/Volumes/Main/libraries/NEW_mysql" -Force
load all required DLLs
Get-ChildItem "/Volumes/Main/libraries/NEW_mysql" | ForEach-Object {
$path = "/Volumes/Main/libraries/NEW_mysql/" + $_.Name
Add-Type -Path $path -PassThru | Out-Null
}

Powershell script returns exception when using ADSI

I get exceptions when executing a Power shell script (v1.0) on Windows Server 2008 (32 bit).
It uses ADSI for searching a virtual directory before its deletion.
I get the following exception:
Exception calling "Find" with "2" argument(s): "Exception from HRESULT: 0x80005008"
At line:1 char:29
+ $iisMgr.psbase.children.find <<<< ("MyVirtualDir", $iisMgr.psbase.SchemaClassName)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
This is the code:
$vDirPath = "IIS://localhost/W3SVC/1/Root"
$iisMgr = [adsi]$vDirPath
$iisMgr.psbase.children.find("MyVirtualDir", $iisMgr.psbase.SchemaClassName)
(edit): from several blogs I read that the IIS6 Management Compatibility role service must be enabled to get the ADSI provider installed, and I already have it enabled, still having this exception...
Do you try with only one parameter ?
$iisMgr.psbase.children.find("MyVirtualDir")
I dont know there, but I've this kind of COM error when I invoke a method with the bad number of arguments.
JP
Just some ideas:
Do you authenticate when doing ADSI interaction?
I guess you are not making use of the Global Catalog as per your example of $vDirPath. In any case have a peek at See How to Modify Attributes That Replicate to the Global Catalog
Try running your Powershell session with elevated user rights (Right-Click Run As Administrator)

Problems using SQL Server 2008 R2 PowerShell extensions outside of SQLPS

I would like to have the SQL Server PowerShell extensions available to me whenever I start PowerShell by loading the snap-ins in my profile.ps1 script. I found an article here with a script example that shows how to do this, and this works fine on my 32-bit Windows XP box.
Unfortunately, on my 64-bit Windows 7 machine, this blows up. If I try to launch this script with the 64-bit PowerShell, I get:
Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 2.
At C:\Users\xxxx\Documents\WindowsPowerShell\profile.ps1:84 char:13
+ Add-PSSnapin <<<< SqlServerCmdletSnapin100
+ CategoryInfo : InvalidArgument: (SqlServerCmdletSnapin100:String
[Add-PSSnapin], PSArgumentException
+ FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand
If I run this instead in a 32-bit PowerShell, I get:
Get-ItemProperty : Cannot find path 'HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds \Microsoft.SqlServer.Management.PowerShell.sqlps' because it does not exist.
At C:\Users\xxxx\Documents\WindowsPowerShell\profile.ps1:39 char:29
+ $item = Get-ItemProperty <<<< $sqlpsreg
+ CategoryInfo : ObjectNotFound: (HKLM:\SOFTWARE\...owerShell.sqlps:String) [Get-ItemProperty], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemPropertyCommand
I'd like to be able to run this in a 64-bit PowerShell if possible. To this end, I tracked down what I thought was the Powershell extension dlls and in a 64-bit Administrator elevated PowerShell I ran:
cd "C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn"
installutil Microsoft.SqlServer.Management.PSProvider.dll
installutil Microsoft.SqlServer.Management.PSSnapins.dll
No dice. Although installutil seemed to indicate success, I still get the "No snap-ins have been registered for Windows PowerShell version 2" error message when I run the script.
Anyone have any suggestions as to where I go from here?
I've used this script without issue on x64 machines. The problem with the x86 invocation is that the script looks for registry keys which on an x64 instance are only accessible from x64 PowerShell. For the x64 invocation you could try registering the snapins since that is the error message you're receiving. Run as administrator...
Change this:
cd $sqlpsPath
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
to this:
cd $sqlpsPath
$framework=$([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory())
Set-Alias installutil "$($framework)installutil.exe"
installutil Microsoft.SqlServer.Management.PSSnapins.dll
installutil Microsoft.SqlServer.Management.PSProvider.dll
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
An even better solution is not use add-pssnapin instead turn sqlps into a module. I have blog post here:
http://sev17.com/2010/07/10/making-a-sqlps-module
Update for SQL Server 2012 - now ships a sqlps module you can install instead of the above blog: http://www.microsoft.com/en-us/download/details.aspx?id=35580
I realise this is a bit of an older question but with a stock standard Windows and SQL Server 2012 install you can just directly use the command Invoke-Sqlcmd without loading anything beforehand as it will auto import the sqlps module. However letting it do that will often cause issues so import the module yourself with the lines below in the same place in your code as you used to use the add-pssnapin commands
$cur = Get-Location
Import-Module 'sqlps' –DisableNameChecking
Set-Location $cur
Similar to that posted on this MS web forum.
The import-module line above changes the current path to something that makes UNC path strings like "\\server\share\path\filename.ext" not work with lots of cmd-lets. So we store the current path before and change it back after the import-module command.
It's possible the snapin assemblies are compiled for x86 only due to dependencies on native 32bit SMO COM objects. If it was possible to run them in a 64bit shell, I'm pretty sure MS would have shipped both x86 and x64 management shells.