C# Renci.SshNet.Sftp Connect throwing ArgumentNullException - c#

I am using Renci.SshNet.Sftp to connect to SFTP. I am getting the following error when I try to call sftpClientObject.Connect(). Please find below the error. It was working fine couple of days ago. Checked the authentication details and it is perfect.
var _sftpClient = new SftpClient(_hostName, _userName, _password);
using (_sftpClient)
{
_sftpClient.Connect();
// Other code to follow
}
Error:
Value cannot be null.
Parameter name: At least one element in the specified array was null.
Exception stacktrace:
at System.Threading.WaitHandle.WaitAny(WaitHandle[] waitHandles, Int32 millisecondsTimeout, Boolean exitContext)
at System.Threading.WaitHandle.WaitAny(WaitHandle[] waitHandles, TimeSpan timeout, Boolean exitContext)
at System.Threading.WaitHandle.WaitAny(WaitHandle[] waitHandles, TimeSpan timeout)
at Renci.SshNet.Session.WaitHandle(WaitHandle waitHandle)
at Renci.SshNet.PasswordAuthenticationMethod.Authenticate(Session session)
at Renci.SshNet.ConnectionInfo.Authenticate(Session session)
at Renci.SshNet.Session.Connect()
at Renci.SshNet.BaseClient.Connect()
at SftpPoller.FileTransferClient.ProcessFilesInSftp(TextWriter log) in
But when I use the following code, it worked:
var methods = new AuthenticationMethod[1];
methods[0] = new PasswordAuthenticationMethod(_userName, _password);
var con = new ConnectionInfo(_hostName, _userName, methods) {Timeout = new TimeSpan(0, 0, 0, 60)};
_sftpClient = new SftpClient(con);
Can anyone help me how to solve this issue?
Thanks

It seems that the only imaginable scenario, when the PasswordAuthenticationMethod.Authenticate can pass an uninitialized wait handle to WaitHandle.WaitAny is when the session is closed while the authentication is ongoing.
If the session is closed due to a timeout, setting a higher timeout can resolve the problem, as you have found yourself.
A simpler code to set the timeout is:
var _sftpClient = new SftpClient(_hostName, _userName, _password);
_sftpClient.ConnectionInfo.Timeout = TimeSpan.FromSeconds(60);
You seem to be using an old version of SSH.NET (probably the version 2013.4.7 available in NuGet). As the relevant part of the code was refactored in later versions, upgrading might solve this problem too. You should do it anyway as the NuGet SSH.NET package is really old.

Related

Npoco new Database fails with "Value cannot be null"

I am trying to update an MVC project from NPoco 3 to NPoco 5.
I could no longer use:
using var db = new Database("DB");
so I changed it to:
using var db = new Database(ConfigurationManager.ConnectionStrings["DB"].ConnectionString, DatabaseType.SqlServer2012, SqlClientFactory.Instance);
and I even tried:
using var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString);
conn.Open();
using var db = new Database(conn);
But no matter what I try,
I just get
Value cannot be null
[Exception: No database type found for the type string specified: 'SqlServerDatabaseType'. Make sure the relevant assembly NPoco.SqlServer is referenced.]
NPoco.DynamicDatabaseType.MakeSqlServerType(String type) +194
NPoco.DatabaseType.Resolve(String typeName, String providerName) +298
NPoco.Database..ctor(DbConnection connection, DatabaseType dbType, Nullable`1 isolationLevel, Boolean enableAutoSelect) +111
How do I open a Database connection in version 5 of NPoco? It doesn't seem to work at all.
(I did notice that I am building to .NET Framework 4.6.1, which is also what NPoco 5 says it works on.)
Thanks for any help if anyone else has seen this.
In a change from Version 3 to Version 5, you must also now add the NuGet package NPoco.SqlServer.

Ghostscript weird lock on dll (An error occured when call to 'gsapi_new_instance' is made: -100)

I have a C#/MVC website for uploading PDFs and when multiple browser instances try to upload at the same time, using Ghostscript.Net v 1.2.1, I get the following error:
Ghostscript.NET.GhostscriptAPICallException: An error occured when call to 'gsapi_new_instance' is made: -100 at Ghostscript.NET.Interpreter.GhostscriptInterpreter.Initialize()
at Ghostscript.NET.Interpreter.GhostscriptInterpreter..ctor(GhostscriptVersionInfo version, Boolean fromMemory)
at Ghostscript.NET.Viewer.GhostscriptViewer.Open(String path, GhostscriptVersionInfo versionInfo, Boolean dllFromMemory)
at Ghostscript.NET.Viewer.GhostscriptViewer.Open(Stream stream, GhostscriptVersionInfo versionInfo, Boolean dllFromMemory)
at Ghostscript.NET.Rasterizer.GhostscriptRasterizer.Open(Stream stream, GhostscriptVersionInfo versionInfo, Boolean dllFromMemory)`
It breaks here:
private Ghostscript.NET.GhostscriptVersionInfo _version = Ghostscript.NET.GhostscriptVersionInfo.GetLastInstalledVersion(Ghostscript.NET.GhostscriptLicense.GPL | Ghostscript.NET.GhostscriptLicense.AFPL, Ghostscript.NET.GhostscriptLicense.GPL);
using (var raster = new GhostscriptRasterizer())
{
raster.Open(fileStream, _version, false);
}
on the Open. This code is called from within a function called by a async Task<ActionResult>. I wonder if the async is somehow breaking it. On the GhostScript site, the closest related answer I could find is to make sure I Close()/Dispose() prior instances -- however this is not my issue as the problem is concomitant instances in different browser sessions calling down into the same .dll (which does have Everyone permissions in IIS).
There is no static variables in reference to any of this, and it happens off an originating HttpPost.
As per https://github.com/jhabjan/Ghostscript.NET/issues/10 , you likely need to change:
raster.Open(fileStream, _version, false);
to:
raster.Open(fileStream, _version, true);

Why am I getting this NullReferenceException in DbConnection.Open()?

I am using System.Data.Common.DbProviderFactories to produce a DbProviderFactory for a dynamically-specified database. One of the supported types is MySQL. What I want is to be able to connect to the MySQL server using Integrated Security. I am setting the proper key-value for the connection string below, but when I do not provide a Username and Password, I always get a NullReferenceException. I am using MySQL 6.9.8.0.
If I provide valid credentials in the two connection string values that you will see commented out, no exception is thrown. Although at that point I suspect I am no longer really using Integrated Security. I have tried setting them to both an empty string and to null, but the exception is still thrown either way.
The "my.ini" file includes this already:
# Enable Windows Authentication
plugin-load=authentication_windows.dll
var factory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
var conn = factory.CreateConnection();
var cmd = conn.CreateCommand();
var csb = new DbConnectionStringBuilder();
//csb.Add("UserID", "root");
//csb.Add("Password", "root");
csb.Add("Server", _serverName);
csb.Add("Database", _dbName);
csb.Add("Connection Timeout", userVars.DatabaseTimeout);
csb.Add("Default Command Timeout", _commandTimeout);
csb.Add("Ssl Mode", "None");
csb.Add("Integrated Security", true);
csb.Add("Persist Security Info", false);
csb.Add("Pooling", true);
csb.Add("Maximum Pool Size", 200);
csb.Add("Minimum Pool Size", 0);
csb.Add("Sql Server Mode", true);
csb.Add("Ignore Prepare", false);
conn.ConnectionString = csb.ConnectionString;
conn.Open(); //<--- exception is thrown internally, here
Executing this code as-is produces a NullReferenceException when Open() is called. As I am stepping in code, this exception pops 4 times on the Open() line, and then steps (just once) into my enclosing try-catch handler as the NRE.
Object reference not set to an instance of an object
server=localhost;database=information_schema;connectiontimeout=60;defaultcommandtimeout=60;sslmode=None;Integrated
Security=True;persistsecurityinfo=False;pooling=True;maxpoolsize=200;minpoolsize=0;sqlservermode=True;ignoreprepare=False
Stack trace:
at
MySql.Data.MySqlClient.Authentication.MySqlNativePasswordPlugin.MoreData(Byte[]
data) at
MySql.Data.MySqlClient.Authentication.MySqlAuthenticationPlugin.AuthenticationChange()
at
MySql.Data.MySqlClient.Authentication.MySqlAuthenticationPlugin.HandleAuthChange(MySqlPacket
packet) at
MySql.Data.MySqlClient.Authentication.MySqlAuthenticationPlugin.Authenticate(Boolean
reset) at MySql.Data.MySqlClient.NativeDriver.Authenticate(String
authMethod, Boolean reset) at
MySql.Data.MySqlClient.NativeDriver.Open() at
MySql.Data.MySqlClient.Driver.Open() at
MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder
settings) at
MySql.Data.MySqlClient.MySqlPool.CreateNewPooledConnection() at
MySql.Data.MySqlClient.MySqlPool.GetPooledConnection() at
MySql.Data.MySqlClient.MySqlPool.TryToGetDriver() at
MySql.Data.MySqlClient.MySqlPool.GetConnection() at
MySql.Data.MySqlClient.MySqlConnection.Open() at AllMax.Sql.Init()
I have also tried directly using the MySql.Data.MySqlClient version of this code, but the exception is still thrown when no User/Pass is provided. What am I missing here?

Invalid handle error when calling MQQueueManager constructor in .NET C#

I've got a seemingly random "The handle is invalid" error when calling the following piece of code :
var properties = new Hashtable();
properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
properties.Add(MQC.HOST_NAME_PROPERTY, "MyHost");
properties.Add(MQC.PORT_PROPERTY, "MyPort");
properties.Add(MQC.CHANNEL_PROPERTY, "MyChannel");
this.QueueManager = new MQQueueManager("MyName", properties);
The environment is .NET Framework 3.5 & MQ Client 7.1
The problem is that this error doesn't occur repeatedly, maybe just 15% of the time, only in the production environment, and I can't seem to reproduce it within my development environment. The only trail I've got is that I know than it is possible for this code to be called simultaneously by two different processes. If it helps, I've also got the following stack trace :
Win32Exception - The handle is invalid
at System.Diagnostics.NtProcessManager.GetModuleInfos(Int32 processId, Boolean firstModuleOnly)
at System.Diagnostics.ProcessManager.GetModuleInfos(Int32 processId)
at System.Diagnostics.Process.get_Modules()
at IBM.WMQ.Nmqi.UnmanagedNmqiMQ.MQCONNX(String pQMgrName, MQCNO& pConnectOpts, Hconn parentHconn, Phconn phconn, Int32& pCompCode, Int32& pReason)
at IBM.WMQ.Nmqi.UnmanagedNmqiMQ.MQCONNX(String pQMgrName, MQConnectOptions pConnectOpts, Phconn phconn, Int32& pCompCode, Int32& pReason)
at IBM.WMQ.MQQueueManager.Connect(String queueManagerName)
at IBM.WMQ.MQQueueManager..ctor(String queueManagerName, Hashtable properties)
...
Any ideas ? Anyone ? :)
This fix might be of help to you. Have you downloaded the latest MQ Client for v7.1?

NetworkCredential error in ASP.NET

I am trying to access a webpage through ASP.NET using the NetworkCredential class. However I keep getting an exception with the following message System.Security.Cryptography.CryptographicException: The handle is invalid
Below is my code on how I am trying to call the function. Any help is greatly appreciated.
C#:
System.Net.WebClient client = new System.Net.WebClient();
client.Credentials = new System.Net.NetworkCredential("Admin", "Nimda");
Stack Trace
[CryptographicException: The handle is invalid.
]
System.Security.SecureString.ProtectMemory() +154
System.Security.SecureString.InitializeSecureString(Char* value, Int32 length) +170
System.Security.SecureString..ctor(Char* value, Int32 length) +65
System.Net.SecureStringHelper.CreateSecureString(String plainString) +6181188
System.Net.NetworkCredential..ctor(String userName, String password) +64
I've just hit this same problem. I was happening locally under the ASP.NET Development Server in VS 2010. When I executed the app under my Windows 7 / IIS 7, it worked just fine. Hope this helps!
Ok this is a bit awkward - I've had a look and the error is down to your windows configuration .... somewhere.
The part of the code that's throwing an Exception is actually an interop call to a function in advapi32.dll, specifically:
int status = Win32Native.SystemFunction040(this.m_buffer, (uint) (this.m_buffer.Length * 2), 0);
if (status < 0)
{
throw new CryptographicException(Win32Native.LsaNtStatusToWinError(status));
}
this.m_encrypted = true;
Calls:
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
internal static extern int SystemFunction040([In, Out] SafeBSTRHandle pDataIn, [In] uint cbDataIn, [In] uint dwFlags);
That's returning an error code, causing your exception.
If you're in a workplace, you might want to talk with your sysadmin/network guys to see if there's anything in your local policies that might cause a failure.
Otherwise, I'd see what happens if you disable your Anti-virus/disable firewall/turn of any 3rd party proxy software.
Basically, anything that overrides default network functionality.
Also, might be worth checking you have all the latest windows updates and that you dont have any virus or malware infection.
Sorry I can't be more specific, but I don't believe this is a .Net/programming error.
This should work in a standard powershell console:
Add-Type -AssemblyName System.Net
$client = New-Object System.Net.WebClient
$netc = New-Object System.Net.NetworkCredential("Admin", "Nimda")
$client.Credentials = $netc
Will be interesting to see if this generates the same invalid handle error.
Edit: Apologies, there was a typo in the 2nd line.

Categories