Key not valid for use in specified state CryptographicException with BouncyCastle - vb.net

Been searching the web and blogs and finding scraps here and there, and trying to put them all together to be able to use System.Security.Cryptography.X509Certificates to digitally sign a PDF file with iTextSharp library.
I have a sign button with the following code behind it:
Dim m As New PdfManipulation
Dim store As New X509Store("MY", StoreLocation.CurrentUser)
store.Open(OpenFlags.ReadOnly Or OpenFlags.OpenExistingOnly)
Dim collection As X509Certificate2Collection = CType(store.Certificates, X509Certificate2Collection)
Dim fcollection As X509Certificate2Collection = CType(collection.Find(X509FindType.FindByTimeValid, DateTime.Now, False), X509Certificate2Collection)
Dim scollection As X509Certificate2Collection = X509Certificate2UI.SelectFromCollection(fcollection, "Test Certificate Select", "Select a certificate from the following list to get information on that certificate", X509SelectionFlag.SingleSelection)
For Each x509 As X509Certificate2 In scollection
m.DigitallySignPdf("C:\Users\my\Desktop\populates.pdf", "C:\Users\my\Desktop\A.pdf", "topmostSubform[0].Page1[0].SignatureField1[0]", x509)
Next x509
store.Close()
The above code works, it opens up my cert store and I choose a certificate. It then passes the certificate to the following PdfManiuplation class for signing.
PdfManipulation Code:
Public Class PdfManipulation
Public Sub DigitallySignPdf(ByVal sourceDocument As String, _
ByVal destinationPath As String, _
ByVal fieldNameToSign As String, _
ByVal signature As X509Certificate2)
Dim reader As New PdfReader(sourceDocument)
Using fout As New FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite)
Using stamper As PdfStamper = PdfStamper.CreateSignature(reader, fout, ControlChars.NullChar)
' appearance
Dim appearance As PdfSignatureAppearance = stamper.SignatureAppearance
appearance.SetVisibleSignature(fieldNameToSign)
' digital signature
Dim akp = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(signature.PrivateKey).Private
Dim es As IExternalSignature = New PrivateKeySignature(akp, "SHA-256")
Dim cp As New Org.BouncyCastle.X509.X509CertificateParser()
MakeSignature.SignDetached(appearance, es, New Org.BouncyCastle.X509.X509Certificate() {cp.ReadCertificate(signature.RawData)}, Nothing, Nothing, Nothing, 0, CryptoStandard.CMS)
stamper.Close()
End Using
End Using
End Sub
End Class
When it gets to
Dim akp = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(signature.PrivateKey).Private
thats when the Exception is thrown. The certificate I choose is the same certificate I sign everything with on my machine, so I know it's good. Any help as to why this would be throwing this error would be greatly appreciated, or a pointer in the right direction.
Also here is my list of Imports:
Imports System.Security.Cryptography
Imports System.Security.Permissions
Imports System.IO
Imports System.Security.Cryptography.X509Certificates
Imports iTextSharp.text.pdf.security
Imports iTextSharp.text
Imports iTextSharp.text.pdf
And have to add a reference to:
System.Security
StackTrace:
System.Security.Cryptography.CryptographicException was unhandled
HResult=-2146893813
Message=Key not valid for use in specified state.
Source=mscorlib
StackTrace:
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.Utils._ExportKey(SafeKeyHandle hKey, Int32 blobType, Object cspObject)
at System.Security.Cryptography.RSACryptoServiceProvider.ExportParameters(Boolean includePrivateParameters)
at Org.BouncyCastle.Security.DotNetUtilities.GetRsaKeyPair(RSA rsa)
at Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(AsymmetricAlgorithm privateKey)
at AccessRequest.PdfManipulation.DigitallySignPdf(String sourceDocument, String destinationPath, String fieldNameToSign, X509Certificate2 signature) in C:\PdfManipulation.vb:line 237
at Form.btnSubmit_Click(Object sender, EventArgs e) in C:\Form.vb:line 251
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at app.My.MyApplication.Main(String[] Args) in 11111.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Also after further testing and looking at the Private key through the IDE, I did notice
signature.privatekey.CspKeyContainerInfo.Exportable = False
would this possibly be the cause of the error and if so, how do make a selected certificate exportable? As the only thing I have seen through searching is actually creating a new certificate and setting the StorageFlag to Exportable and I am not trying to create a new certificate. I am just trying to use the selected certificate.

The error was being caused by the fact that Private Certificate was NOT exportable.
I had been wondering through all my testing why I was not being prompted even once for my smart card pin for the certificate I was choosing. Which lead me to finally selecting one of my certificates that I know would not ask for pin, and viola, the pdf exported and was signed. Even stepped through the code to view the certificate privatekey property and this time it read
signature.privatekey.CspKeyContainerInfo.Exportable = True
Which finally matched another form i discovered, that stated they fixed their error by making the private key exportable. Now all I have to do is figure out how to make this work with certificates that should be asking me for my pin. If i ever discover that problem I will post back here.

You are right pointing out about the certificate not being exportable
So change:
Dim akp =
Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(signature.PrivateKey).Private
Dim es As IExternalSignature = New PrivateKeySignature(akp, "SHA-256")
to just:
Dim es As IExternalSignature = New
security.X509Certificate2Signature(signature, "SHA-256")

Related

Visual basic with external .ocx control => access violation

I'm new to this site and I'm going to start immediately with a question.
Currently I'm working on a thesis but I'm a stuck at this moment. I've been asked to control an IP-camera via Beckhoff Twincat3. As this is based on visual studio, I thought it might be a good idea to start in visual basic to test and debug everything I code. Everything I do results in AccessViolation.
System.AccessViolationException was unhandled
HResult=-2147467261
Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=mscorlib
StackTrace:
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at RASplus_WatSearLib._DRASplus_WatSear.setCameraMap(Int16 nCamNum, Int16 postKey, String szSiteName, String szAddr, Int16 nHostCam, String szUser, String szPasswd, Int16 port, Boolean mode, Boolean bUseModem, Boolean useDvrns, String szDvrnsAddr, Int16 dvrnsPort, Int16 audioPort)
at AxRASplus_WatSearLib.AxRASplus_WatSear.setCameraMap(Int16 nCamNum, Int16 postKey, String szSiteName, String szAddr, Int16 nHostCam, String szUser, String szPasswd, Int16 port, Boolean mode, Boolean bUseModem, Boolean useDvrns, String szDvrnsAddr, Int16 dvrnsPort, Int16 audioPort)
at activex_camera.Form1.Button1_Click(Object sender, EventArgs e) in C:\Users\BECKHOFF stage\documents\visual studio 2010\Projects\activex camera\activex camera\Form1.vb:line 41
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at activex_camera.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
I'm currently trying to connect with the camera and it results each time in a AccessViolation.
myCam.setCameraMap(i, CShort(0), "10.199.217.144", "10.199.217.144", i, "admin", "", CShort(8016), False, False, False, "dvrnames.net", 10088, 8116)
I hope someone can get me back on track. If .ocx or other files needed, please do not hesitate to contact me.
I asked my teacher if he knew what was wrong and he came up with this :
In the program, I was working with an 'instance' of the activex-control. This resulted in a accessviolation. He fixed it by using the direct control.
After all it made sense. ;)
Sincerely
GiovanniVanAssche

Get "ALL" Filename and Path from a Running Process VB.net

IT;S VB.NET not C# and i don't know how to exchange source from C# to VB.NET, THANKS
I want to get all paths from all running processes.
This is my source so far:
For Each p As Process In Process.GetProcesses
Try
ListBox1.Items.Add(p.MainModule.FileName.ToString)
Catch ex As Exception
RichTextBox1.Text = ex.Message
End Try
Next
But I can't get all path folders of the running processes.
If I examine the ex.Message, the response is like this
Unable to enumerate the process modules.
But if I not using ex.Message, the response is like this :
System.ComponentModel.Win32Exception was unhandled
ErrorCode=-2147467259
HResult=-2147467259
Message=A 32 bit processes cannot access modules of a 64 bit process.
NativeErrorCode=299
Source=System
StackTrace:
at System.Diagnostics.NtProcessManager.GetModuleInfos(Int32 processId, Boolean firstModuleOnly)
at System.Diagnostics.NtProcessManager.GetFirstModuleInfo(Int32 processId)
at System.Diagnostics.Process.get_MainModule()
at Anti_Cheat.Form1.Button6_Click(Object sender, EventArgs e) in c:\users\adiyatma\documents\visual studio 2012\Projects\Anti Cheat\Anti Cheat\Form1.vb:line 40
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at Anti_Cheat.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Can anyone help me?
Take a look at the so-question How to get the full path of running process?
Instead of
ListBox1.Items.Add(p.MainModule.FileName.ToString)
try
ListBox1.Items.Add(p.Modules(0).FileName.ToString)
Edit:
Have you tried to evaluate the property of different processes directly? Maybe there is a certain process you cannot access, resulting in the error described.
You can try to iterate trough the processes one by one by creating the following loop:
For Each p As System.Diagnostics.Process In System.Diagnostics.Process.GetProcesses()
Try
Console.WriteLine(p.Modules(0).FileName)
Catch ex As Exception
Console.WriteLine(String.Format("{0}: Error - {1}", p.ProcessName, ex.Message))
End Try
Next
By doing so, you should be able to determine the processes you're not allowed to access and get a couple of processes you should be able to experiment with.
Mate the problem is obvious, you are targeting 32-bit but are testing your app on a computer that has 64-bit installed system, that's why you get the error.
Message=A 32 bit processes cannot access modules of a 64 bit process.
to fix this issue you should make the target 64-bit, there IS NO SOLUTION for this...
if you know the famous procexp (sysinternals) it has two separate application, when the system is 32-bit it lauches an instance of 32-bit, but when it is 64-bit it lauches another separate process for the system...
so if you want to deal with this issue, you have to make two instances for system compability,
Hope this is helpful

Running sql script from Windows Forms Application

I am building a VB.NET desktop application in VS2013 that uses a .mdf file created in SQL Server 2012. I have the .mdf file imported in to the application. Along with the datagridviews I am using to view/modify the database tables I need to execute a SQL script when the user clicks on a button.
I have been trying several examples I've found, without any luck. I'm getting a FileLoadException error on the ExecuteNonQuery line:
An unhandled exception of type 'System.IO.FileLoadException' occurred
in mscorlib.dll
Additional information: Mixed mode assembly is built against version
'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime
without additional configuration information.
The "Troubleshooting tips" section has "Make sure that the file is a valid .NET Framework assembly". I clicked on that link, but the information there isn't very helpful to me, as I really am not understanding what it's saying.
I've tried these two examples so far:
Dim sqlScript As String = "C:\HL_Time_Entry_Reporting\SQL Scripts\stage_employee_hours_load.sql"
Dim connString As String = "Server=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\HL_Time_Entry_Reporting\Database\hours_analysis.mdf"
Dim connectionString As String = connString,
scriptText As String = sqlScript
Dim sqlConnection As New SqlConnection(connectionString)
Dim svrConnection As New ServerConnection(sqlConnection)
Dim server As New Server(svrConnection)
server.ConnectionContext.ExecuteNonQuery(scriptText)
from this site. And
Dim sqlConnectionString As String = "Server=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\HL_Time_Entry_Reporting\Database\hours_analysis.mdf"
Dim file As New FileInfo("C:\HL_Time_Entry_Reporting\SQL Scripts\stage_employee_hours_load.sql")
Dim script As String = file.OpenText().ReadToEnd()
Dim conn As New SqlConnection(sqlConnectionString)
Dim server As New Server(New ServerConnection(conn))
server.ConnectionContext.ExecuteNonQuery(script)
from this site.
One thing is, I'm not confident I have the correct connection string for this. That's the connection string I have for the datagridviews, which works fine, but is that also what I should use to connect for the sql script file as well?
UPDATE
Per request, here is the stack trace:
at System.Reflection.RuntimeAssembly.GetType(RuntimeAssembly
assembly, String name, Boolean throwOnError, Boolean ignoreCase,
ObjectHandleOnStack type) at
System.Reflection.RuntimeAssembly.GetType(String name, Boolean
throwOnError, Boolean ignoreCase) at
System.Reflection.Assembly.GetType(String name, Boolean throwOnError)
at
Microsoft.SqlServer.Management.Common.ServerConnection.GetStatements(String
query, ExecutionTypes executionType, Int32& statementsToReverse) at
Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String
sqlCommand, ExecutionTypes executionType) at
Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String
sqlCommand) at test.main.btnLoadMasterData_Click(Object sender,
EventArgs e) in C:\Users\marky\Documents\Visual Studio
2013\Projects\Hours Analysis\Hours Analysis\Form1.vb:line 212 at
System.Windows.Forms.Control.OnClick(EventArgs e) at
System.Windows.Forms.Button.OnClick(EventArgs e) at
System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at
System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
button, Int32 clicks) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.ButtonBase.WndProc(Message& m) at
System.Windows.Forms.Button.WndProc(Message& m) at
System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr
hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at
System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr
dwComponentID, Int32 reason, Int32 pvLoopData) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.Run(ApplicationContext context) at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[]
commandLine) at test.My.MyApplication.Main(String[] Args) in
17d14f5c-a337-4978-8281-53493378c1071.vb:line 81 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at System.AppDomain.ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity, String[] args) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()
UPDATE #2
As suggested, I added the startup tag in this SO question to my appconfig file but got a new error on the line "Dim server As New Server(New ServerConnection(conn))" in the second code example. It's a TypeInitializationException. Here's the info:
An unhandled exception of type 'System.TypeInitializationException'
occurred in System.Data.dll
Additional information: The type initializer for
'System.Data.SqlClient.SqlConnection' threw an exception.
Stack trace:
at System.Data.SqlClient.SqlConnection..ctor() at
System.Data.SqlClient.SqlConnection..ctor(String connectionString,
SqlCredential credential) at
System.Data.SqlClient.SqlConnection..ctor(String connectionString)
at test.main.btnLoadMasterData_Click(Object sender, EventArgs e) in
C:\Users\marky\Documents\Visual Studio 2013\Projects\Hours
Analysis\Hours Analysis\Form1.vb:line 210 at
System.Windows.Forms.Control.OnClick(EventArgs e) at
System.Windows.Forms.Button.OnClick(EventArgs e) at
System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at
System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
button, Int32 clicks) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.ButtonBase.WndProc(Message& m) at
System.Windows.Forms.Button.WndProc(Message& m) at
System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr
hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at
System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr
dwComponentID, Int32 reason, Int32 pvLoopData) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.Run(ApplicationContext context) at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[]
commandLine) at test.My.MyApplication.Main(String[] Args) in
17d14f5c-a337-4978-8281-53493378c1071.vb:line 81 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at System.AppDomain.ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity, String[] args) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()
It looks like you may be using an obsolete version of the SMO library, as explained here: https://stackoverflow.com/a/11286124/109122.
Update:
If the config setting recommended at the link does not work, try this simpler one instead:
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
</startup>
Unfortunately, it appears that the config file changes do not fix all cases.

AccessViolationException was unhandled?

I'm working on a directory Project where in when the program is not being use or idle for 3 minutes, a form that act as stand-by screen that plays a video will show (I use AxWindowsMediaPlayer). By clicking anywhere in the form, the stand-by screen will close and will be back to the main form.
The program works fine but SOMETIMES during the closing of stand-by screen form, the application crashes with the error:
AccessViolationException was unhandled. Attempted to read or write
protected memory. This is often an indication that other memory is
corrupt.
and this is the complete error detail:
System.AccessViolationException was unhandled
Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.RunDialog(Form form)
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at System.Windows.Forms.Form.ShowDialog()
at BuildingDirectory.main.tmrTime_Tick(Object sender, EventArgs e) in C:\Users\pc\Documents\Visual Studio 2010\Projects\testing\BuildingDirectory\BuildingDirectory\main.vb:line 128
at System.Windows.Forms.Timer.OnTick(EventArgs e)
at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at BuildingDirectory.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
The weird thing is, the line of code where the error is pointing, is enclosed in try catch block specifically catching AccessViolationException(it was exception before but still encountered the problem):
Private Sub tmrTime_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrTime.Tick
Try
lblTime.Text = TimeOfDay
If standby = 2 Then
standby += 1
standByScreen.ShowDialog() ---> this is where the error is pointing to
Else
standby += 1
End If
Catch ex As AccessViolationException
MessageBox.Show(ex.ToString)
End Try
End Sub
Please help me, thank you
This might be due to early binding of the standByScreen variable. Note that the error is caused due to the System.Windows.Forms class
Try:
Dim stndByScreen As Object
stndByScreen = standByScreen
stndByScreen.ShowDialog()
instead of directly using standByScreen

PictureBox throws "Parameter is not valid" ArgumentException upon tab keypress

I have a form where the user can first scan to a bitmap. When scan is done, and the bitmap is loaded, I have 4 text boxes that are then enabled. Next to each text box, I have a button called "Cut from image". When the user clicks the button, they can click and drag in the bitmap to get the selected text using MODI.
This works perfect except for one annoying bug: When I click a "Cut from image" button and drag a square, it gets the information nicely to the text box. Then, if i click to the next text box, it goes very well, but if I use the tab key to leave the field, I get a "Parameter is not valid" ArgumentException and it does not show any help for where in the code the crash is made. I can tab around in the form with no problems at all, but once the bitmap is scanned, it crashes like 9 out of 10 times when I use the tab key.
I tried to override the tab key (just for debugging) using this:
Protected Overrides Function ProcessTabKey(ByVal forward As Boolean) As Boolean
MsgBox("TAB is currently disabled!")
Return False 'Tried True as well, just in case
End Function
...but it still crashes.
Any suggestions about what's wrong? Since I don't know where to begin debugging I can't tell what code to show.
EDIT 1
Here is the stack trace for the ArgumentException that gets thrown:
at System.Drawing.Image.get_Width()
at System.Drawing.Image.get_Size()
at System.Windows.Forms.PictureBox.ImageRectangleFromSizeMode(PictureBoxSizeMode mode)
at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at ORC_Testing.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
EDIT 2
Here is how I'm scanning/loading the image:
Dim filename As Collection
filename = TwainHandler.ScanImages("c:\scan\", "tif")
Dim ScannedFile As Image = Image.FromFile(filename(1))
PictureBox1.Image = ScannedFile
PictureBox1.Width = ScannedFile.Width
' etc.
Your problem is likely that, at some point, you are calling the Dispose method on one of your Image objects. When you call Image.Dispose, it deletes the underlying image data from memory, so the Image object still exists, but is invalid because it no longer contains an actual image. When you set the PictureBox.Image property to a loaded Image object, the PictureBox control assumes that the Image object will remain valid so that it can reuse it later any time the control needs to repaint itself to the screen. For instance:
Dim myImage As Image = Image.FromFile("file path")
PictureBox1.Image = myImage
PictureBox1.Refresh() ' This works
myImage.Dispose()
PictureBox1.Refresh() ' This throws an exception because it tries to access the disposed Image object
The PictureBox control will automatically dispose of the image for you when it is disposed, so you don't need to worry about disposing it yourself. The only time you should be disposing your images is when you are not giving them to any other objects for later use.
Here is my solution, somebody could use it, even though the question is old.
Dim myImage As Image = Image.FromFile("file path")
PictureBox1.Image = myImage.clone // Use clone to give a new copy not a reference of image
PictureBox1.Refresh() // This works
myImage.Dispose()
PictureBox1.Refresh() // This works also because we've a copy not reference
PictureBox1.Image = myImage.Clone
This way you are using a copy of the image so it does not matter what happens with the original