Invalid handle error when calling MQQueueManager constructor in .NET C# - 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?

Related

C# Renci.SshNet.Sftp Connect throwing ArgumentNullException

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.

GetPrintJobInfoCollection() Exception sometimes

This code that might seem useless it reproduces the problem. Another application is using
http://printqueuewatch.codeplex.com/ to be notified when a print job is sent to printer.
It works but sometimes when you send a print job it crashes here GetPrintJobInfoCollection.
I have pasted the inner exception. To reproduce I send with Notepad++ or my application a small text file about 20 times until i get a crash.
If after the crash I call GetPrintJobInfoCollection it works successfully or I retry.
Any suggestion how to fix this ?
while (true)
{
Thread.Sleep(10);
LocalPrintServer server = new LocalPrintServer();
var q = server.GetPrintQueue("vp1");
q.Refresh();
// Debug.WriteLine(q.IsBusy);
PrintJobInfoCollection infos = null;
infos = q.GetPrintJobInfoCollection();
}
Error in
System.NullReferenceException was unhandled Message=Object reference
not set to an instance of an object. Source=System.Printing
StackTrace:
at MS.Internal.PrintWin32Thunk.AttributeNameToInfoLevelMapping.InfoLevelCoverageList.Release()
at MS.Internal.PrintWin32Thunk.EnumDataThunkObject.GetPrintSystemValuesPerPrintJobs(PrintQueue
printQueue, Queue`1 printObjectsCollection, String[] propertyFilter,
UInt32 firstJobIndex, UInt32 numberOfJobs)
at System.Printing.PrintJobInfoCollection..ctor(PrintQueue printQueue, String[] propertyFilter)
at System.Printing.PrintQueue.GetPrintJobInfoCollection()
at WpfApplication7.MainWindow.button2_Click(Object sender, RoutedEventArgs e) in
According to this MSDN article you shouldn't use System.Printing namespace.
Classes within the System.Printing namespace are not supported for use
within a Windows service or ASP.NET application or service. Attempting
to use these classes from within one of these application types may
produce unexpected problems, such as diminished service performance
and run-time exceptions. If you want to print from a Windows Forms
application, see the System.Drawing.Printing namespace.
I am thinking that your problem is due to resource leak. The LocalPrintServer class seems to be an unmanaged resource and needs to be disposed.

Attempted to read or write protected memory in a .NET application

I'm having troubles at implementing and ASP .Net Application in IIS 6 Server.
When the user tries to open a web page that access the database, iis server throws "Attempted to read or write protected memory" this is the StackTrace:
System.AccessViolationException: Attempted to read or write protected
memory. This is often an indication that other memory is corrupt.
at Oracle.DataAccess.Client.OpsPrm.ResetValCtx(OpoPrmValCtx* pOpoPrmValCtx, Int32 ctxSize)
at Oracle.DataAccess.Client.OracleParameter.ResetCtx(Int32 arraySize)
at Oracle.DataAccess.Client.OracleParameter.PreBind(OracleConnection
conn, IntPtr errCtx, Int32 arraySize)
at Oracle.DataAccess.Client.OracleCommand.ExecuteReader(Boolean requery, Boolean fillRequest, CommandBehavior behavior)
at Oracle.DataAccess.Client.OracleCommand.ExecuteReader()
at Oracle.DataAccess.Client.OracleCommand.ExecuteScalar()
at Tenaris.FSA.OracleProvider.OracleProvider.ExecuteScalar(String commandToExecute, CommandType commandType, DbParameter[] parameters)
in C:\Congelados FSA\FSA 1er Entregable
05052013\Tenaris.FSA.OracleProvider\OracleProvider.cs:line 223
at Tenaris.FSA.DAC.Providers.DataAccessManager.ExecuteScalar(String
commandToExecute, CommandType commandType, DbParameter[] parameters)
in C:\Congelados FSA\FSA 1er Entregable
05052013\Tenaris.FSA.DataAccessComponent\Providers\DataAccessManager.cs:line
59
at Tenaris.FSA.DAC.Repository.AppointmentWayClientDAL.GetCountRegisters(Boolean
onlyEnabled) in C:\Congelados FSA\FSA 1er Entregable
05052013\Tenaris.FSA.DataAccessComponent\Repository\AppointmentWayClientDAL.cs:line
39
at Tenaris.FSA.BusinessComponents.BusinessProcess.AppointmentWayClientManager.GetCountRegisters(Boolean
onlyEnabled) in C:\Congelados FSA\FSA 1er Entregable
05052013\Tenaris.FSA.BusinessComponents\BusinessProcess\AppointmentWayClientManager.cs:line
28
What's rare, because that error is not supposed to appear in managed code, and the previous version of the site is working fine. I've done several tests, like compiling the app in an x86 platform pc, copied the web.config from the functional version, copied the Oracle.DataAccess dll from the functional version, but the error still showing.
Another thing you should know is that there is a page that, actually succeded in filling a dropdownlist, but then the page has to fill a gridview and there appears the above exception.
I could finally solve the issue, another developer used a "using" clause while creating OracleParameters, it was like:
using(OracleParameter prm = SomeMethodThatCreatesIt(value,paramName))
{
//extracode
myCommand.Parameters.Add(prm);
}
So the code had to change to:
OracleParameter prm = SomeMethodThatCreatesIt(value,paramName);
//extracode
myCommand.Parameters.Add(prm);
As you can see in the stacktrace, the problem were at some process for parameters.
So, The code was Disposing the object before using it. What I can't understand is why is this even working in a console application that was one of my tests, but well it is working now, Thank you everyone
the system has run out of ram to load it so when it tries to take more from other applications that is protected memory so get more ram

C# Application being blocked by Anti-Virus?

I have a Payroll System that is written using Visual C# Express. I have actually finished coding it already and published it. But whenever I install it on the laptop it is being blocked by Avast! Antivirus as suspicious and stops the process. After that the applciation cannot be started event though it was installed saying that a file is missing. It has this in its details :
PLATFORM VERSION INFO
Windows : 6.1.7601.65536 (Win32NT)
Common Language Runtime : 4.0.30319.296
System.Deployment.dll : 4.0.30319.1 (RTMRel.030319-0100)
clr.dll : 4.0.30319.296 (RTMGDR.030319-2900)
dfdll.dll : 4.0.30319.1 (RTMRel.030319-0100)
dfshim.dll : 4.0.31106.0 (Main.031106-0000)
SOURCES
Deployment url : file:///C:/Users/John%20Jayson/AppData/Roaming/Microsoft/Windows/Start%20Menu/Programs/IT%20Box%20Incorporated/Payroll%20System.appref-ms%7C
ERROR SUMMARY
Below is a summary of the errors, details of these errors are listed later in the log.
* Activation of C:\Users\John Jayson\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\IT Box Incorporated\Payroll System.appref-ms| resulted in exception. Following failure messages were detected:
+ Activation failed.
+ The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
COMPONENT STORE TRANSACTION FAILURE SUMMARY
No transaction error was detected.
WARNINGS
There were no warnings during this operation.
OPERATION PROGRESS STATUS
* [2/15/2013 12:39:05 PM] : Activation of C:\Users\John Jayson\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\IT Box Incorporated\Payroll System.appref-ms| has started.
* [2/15/2013 12:39:05 PM] : Performing necessary update check as specified by the deployment.
ERROR DETAILS
Following errors were detected during this operation.
* [2/15/2013 12:39:05 PM] System.Deployment.Application.DeploymentException (Activation)
- Activation failed.
- Source: System.Deployment
- Stack trace:
at System.Deployment.Application.ComponentStore.ActivateApplication(DefinitionAppId appId, String activationParameter, Boolean useActivationParameter)
at System.Deployment.Application.SubscriptionStore.ActivateApplication(DefinitionAppId appId, String activationParameter, Boolean useActivationParameter)
at System.Deployment.Application.ApplicationActivator.Activate(DefinitionAppId appId, AssemblyManifest appManifest, String activationParameter, Boolean useActivationParameter)
at System.Deployment.Application.ApplicationActivator.ProcessOrFollowShortcut(String shortcutFile, String& errorPageUrl, TempFile& deployFile)
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
--- Inner Exception ---
System.IO.FileNotFoundException
- The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
- Source: System.Deployment
- Stack trace:
at System.Deployment.Application.NativeMethods.CorLaunchApplication(UInt32 hostType, String applicationFullName, Int32 manifestPathsCount, String[] manifestPaths, Int32 activationDataCount, String[] activationData, PROCESS_INFORMATION processInformation)
at System.Deployment.Application.ComponentStore.ActivateApplication(DefinitionAppId appId, String activationParameter, Boolean useActivationParameter)
COMPONENT STORE TRANSACTION DETAILS
No transaction information is available.
So before the window saying Application cannot be started pops up A notification windows from Avast says that it is a Win32:Evo-gen threat.
What should I do?
It also happened with me, I have project in c#, I am using external Ribbon35 control in my project which has option in tabs like creating, scanning, processing etc. When I added 4 new tabs and added buttons on tabs it suddenly shows [Win32:Evo-gen] and exe was blocked. Please remember I did not rename Tab Names instead they were on its default names like [RibbonTab1, captiontext = Scanning] I though Antivirus would have thinking this as malicious behavior from my application, I rename all tabs as like its behavior and problem gone.
(May be hackers don't care about naming controls as their behaviors)
I also faced this problem while working on a project using VB.NET, Then I changed my recent updates back to identify the problem. The problem was with an "Insert" statement where I used below code to get the date value from a Datetimepicker Control directly.
dtpJD.Value.ToString("yyyy/MM/dd HH:mm:ss")
Then I replaced it with a Variable in Insert statement and everything was fine.
parJDDate = dtpJD.Value.ToString("yyyy/MM/dd HH:mm:ss")
found one clue..
-when my application run from folder with foreign characters in the name
then Avast will block it.
-After I renamed folder to contains only eng chars. Problem was solved.
Buddy, it detects as a virus becouse it contains payment, and it thinks you got a ransomware, you can add to exclusions i think, but i never used avast, it's not the best antivirus, if u want a free antivirus with good protection use comodo, or if u want best: kaspersky, or you should use another method, but i prefer to uninstall avast and install a better antivirus software, check the site of the AV Test
and choose the best protection level what you need
Regards

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