CodeGuru Forums -
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic Newsletters VB Forums Developer.com


Newest CodeGuru.com Articles:

  • SQL Server Modeling Services with Microsoft Visual Studio 2010 Beta 2
  • Faltering Windows support
  • Internet Explorer 8 Click Clever Click Safe
  • Release Candidate 2 for ASP.NET MVC 2

  • Search CodeGuru:
     



    Go Back   CodeGuru Forums > .NET Programming > C-Sharp Programming
    FAQ Members List Calendar Search Today's Posts Mark Forums Read

    C-Sharp Programming Post questions, answers, and comments about C#.

    Reply
     
    Thread Tools Search this Thread Rate Thread Display Modes
      #1    
    Old September 30th, 2008, 03:21 AM
    MontgomeryBurns's Avatar
    MontgomeryBurns MontgomeryBurns is offline
    Member
     
    Join Date: Jul 2003
    Location: Springfield
    Posts: 172
    MontgomeryBurns is on a distinguished road (10+)
    UnauthorizedAccessException when accessing Virtual COM port

    Hi,
    My application opens a virtual COM port to access an USB device. (I'm using CDC ACM Port Driver by Thesycon GmbH).
    My app opens the port and closes it correctly, if I disconnect the USB cable from the device before calling SerialPort.Close(), then the UnauthorizedAccessException is thrown. Notice that it's not the Close() that throws the exception. It's a separate thread (which is not created from my code) that throws it.
    This is what the IDE's output window shows:
    Code:
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\Microsoft.VisualStudio.HostingProcess.Utilities\9.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.HostingProcess.Utilities.dll'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Windows.Forms\2.0.0.0__b77a5c561934e089\System.Windows.Forms.dll'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Drawing\2.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\Microsoft.VisualStudio.HostingProcess.Utilities.Sync\9.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.HostingProcess.Utilities.Sync.dll'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\9.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\Temp\WindowsFormsApplication3\WindowsFormsApplication3\bin\Debug\WindowsFormsApplication3.vshost.exe'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Core\3.5.0.0__b77a5c561934e089\System.Core.dll'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Xml.Linq\3.5.0.0__b77a5c561934e089\System.Xml.Linq.dll'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Data.DataSetExtensions\3.5.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_32\System.Data\2.0.0.0__b77a5c561934e089\System.Data.dll'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Deployment\2.0.0.0__b03f5f7f11d50a3a\System.Deployment.dll'
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Xml\2.0.0.0__b77a5c561934e089\System.Xml.dll'
    The thread 0xfb4 has exited with code 0 (0x0).
    The thread 0xfbc has exited with code 0 (0x0).
    'WindowsFormsApplication3.vshost.exe' (Managed): Loaded 'C:\Temp\WindowsFormsApplication3\WindowsFormsApplication3\bin\Debug\WindowsFormsApplication3.exe', Symbols loaded.
    >>>>> System.IO.Ports.SerialPort.Open() returned without any error
    The thread 0xeec has exited with code 0 (0x0).
    >>>>> System.IO.Ports.SerialPort.Close() returned without any error
    The thread 0x814 has exited with code 0 (0x0).
    The thread 0x888 has exited with code 0 (0x0).
    A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.dll
    An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.dll
    
    Additional information: Access to the port is denied.
    
    The program '[0xF50] WindowsFormsApplication3.vshost.exe: Managed' has exited with code -532459699 (0xe0434f4d).
    Is there a way to prevent this exception to be thrown?
    __________________
    Mr. Burns

    Last edited by MontgomeryBurns; September 30th, 2008 at 03:25 AM.
    Reply With Quote
      #2    
    Old February 1st, 2009, 10:07 PM
    RaleTheBlade's Avatar
    RaleTheBlade RaleTheBlade is offline
    Member
     
    Join Date: Jul 2007
    Location: Illinois
    Posts: 453
    RaleTheBlade has a spectacular aura about (150+) RaleTheBlade has a spectacular aura about (150+)
    Re: UnauthorizedAccessException when accessing Virtual COM port

    Ive got the exact same problem. Its occuring in a Win32 component when SetCommMask is called (which runs Async and is where the exception is coming from) and then WaitCommEvent is called. I wrote a small Win32 serial port class in C++ that acts right on the Windows API and didnt called either the SetCommMask or the WaitCommEvent functions and when I called ReadFile to read data from the buffer it would throw an exception that I could catch.

    I created a wrapper class for the C++ class in C# but I cannot get it to act reliably. My stack pointers and stuff keep getting moved because I am forced to use "unsafe" code.

    I guess thats the only REAL way to get around it. As far as I can tell its a bug (a NASTY one albeit) in the .NET Framework.
    __________________
    R.I.P. 3.5" Floppy Drives
    "I know not with what weapons World War III will be fought, but World War IV will be fought with sticks and stones." - Albert Einstein
    Reply With Quote
      #3    
    Old February 2nd, 2009, 03:19 AM
    MontgomeryBurns's Avatar
    MontgomeryBurns MontgomeryBurns is offline
    Member
     
    Join Date: Jul 2003
    Location: Springfield
    Posts: 172
    MontgomeryBurns is on a distinguished road (10+)
    Re: UnauthorizedAccessException when accessing Virtual COM port

    I solved my problem adding a config file to my Visual Studio C# project. My app.config file is this:
    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    	<runtime>
    		<legacyUnhandledExceptionPolicy enabled="true"/>
    	</runtime>
    </configuration>
    as explained here:
    http://connect.microsoft.com/VisualS...edbackID=98348
    __________________
    Mr. Burns
    Reply With Quote
      #4    
    Old February 2nd, 2009, 05:32 AM
    darwen's Avatar
    darwen darwen is offline
    Elite Member
    Power Poster
     
    Join Date: Jan 2002
    Location: Scaro, UK
    Posts: 5,878
    darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+)
    Re: UnauthorizedAccessException when accessing Virtual COM port

    Or even better, I'd suggest trapping the exception (try/catch) and handling it. Microsoft (in the link posted by MontgomeryBurns) say that they thought it better to throw an exception to inform the client application that something was wrong - and I agree with them.

    If I were writing an application using a USB port I'd want it to know if someone pulled the plug out half way through operation...

    Also

    Code:
    My stack pointers and stuff keep getting moved because I am forced to use "unsafe" code.
    You're never FORCED to use unsafe code. You can p/invoke using IntPtr-s and pin arrays manually using GCHandle.Alloc(..., GCHandleType.Pinned). If you're using asynchronous operation you should then handle the completed event to GCHandle.Free the pinned pointer once the asynchronous write has finished.

    Darwen.
    __________________
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

    Last edited by darwen; February 2nd, 2009 at 05:36 AM.
    Reply With Quote
      #5    
    Old February 2nd, 2009, 06:58 AM
    MontgomeryBurns's Avatar
    MontgomeryBurns MontgomeryBurns is offline
    Member
     
    Join Date: Jul 2003
    Location: Springfield
    Posts: 172
    MontgomeryBurns is on a distinguished road (10+)
    Re: UnauthorizedAccessException when accessing Virtual COM port

    Quote:
    Or even better, I'd suggest trapping the exception (try/catch) and handling it.
    That's what I'd prefer, either. But you cannot trap the exception since it is thrown by a thread created somewhere else of my code. From the link:
    Quote:
    exception gets thrown on the event loop thread
    __________________
    Mr. Burns
    Reply With Quote
      #6    
    Old February 2nd, 2009, 07:04 AM
    darwen's Avatar
    darwen darwen is offline
    Elite Member
    Power Poster
     
    Join Date: Jan 2002
    Location: Scaro, UK
    Posts: 5,878
    darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+) darwen has a brilliant future (2000+)
    Re: UnauthorizedAccessException when accessing Virtual COM port

    What's the 'event loop thread' ?

    If you want exceptions in a worker thread to be translated back to the thread which originally started the worker thread you have 2 options :

    (1) Trap them yourself using try...catch and implement a mechanism to pass it back to the main thread.
    (2) Use asynchronous delegates (i.e. BeginInvoke of a delegate). The exception is trapped by the framework on the thread that executes the delegate and automatically re-thrown in response to an EndInvoke on whichever thread EndInvoke is called on.

    Darwen.
    __________________
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.
    Reply With Quote
      #7    
    Old February 2nd, 2009, 08:58 AM
    MontgomeryBurns's Avatar
    MontgomeryBurns MontgomeryBurns is offline
    Member
     
    Join Date: Jul 2003
    Location: Springfield
    Posts: 172
    MontgomeryBurns is on a distinguished road (10+)
    Re: UnauthorizedAccessException when accessing Virtual COM port

    I mean that that exception is not thrown by my main thread nor any thread created from my code. I tried trapping it like this:
    Code:
    		[STAThread]
    		static void Main(string[] argv)
    		{
    			try
    			{
    				Application.EnableVisualStyles();
    				Application.SetCompatibleTextRenderingDefault(false);
    				Application.Run(new MainForm(argv));
    			}
    			catch(Exception e)
    			{
    				MessageBox.Show(e.Message); // never goes here!
    			}
    		} // while debugging exception is thrown when pressing 'Debug Step' here
    but the Exception is not trapped, because it is thrown later. While debugging, I press 'Step' when the cursor is on the last closing brace, only then the exception is thrown.
    Quote:
    What's the 'event loop thread' ?
    I just quoted the text from the Microsoft answer in the microsoft connect website. I don't know exactly what he means, but I'm sure that the thread that throws the exception is not in my code (so I don't know how to trap it) because I identified it using the debugger in the 'Thread window'.
    So how can I trap an exception thrown by other threads created by the Framework?
    __________________
    Mr. Burns
    Reply With Quote
      #8    
    Old February 3rd, 2009, 12:21 AM
    RaleTheBlade's Avatar
    RaleTheBlade RaleTheBlade is offline
    Member
     
    Join Date: Jul 2007
    Location: Illinois
    Posts: 453
    RaleTheBlade has a spectacular aura about (150+) RaleTheBlade has a spectacular aura about (150+)
    Re: UnauthorizedAccessException when accessing Virtual COM port

    I ended up using some interop to catch this toughy. The thread that throws the exception is occurring in the function SetCommMask(HANDLE, DWORD) in kernel32.dll. This function spins off a separate thread to monitor the internal windows buffer where bytes are received from the port and it triggers WaitCommEvent and that is where your SerialPort.DataReceived event comes from.

    Problem is it runs on a thread that is NOT part of user code (this is probably the "event loop thread" you noted earlier) so catching the exception through C# is virtually impossible without the app.config wrench noted by the OP. You either have to do that, or use some interop with the kernel32.dll to avoid calling the SetCommMask function and avoid creating that background thread that throws the exception. I did this, and called CreateFile(HANDLE, LPDCB), GetCommState(HANDLE, LPDCB), SetCommState(HANDLE, LPDCB), and ReadFile(HANDLE, void*, DWORD, LPDWORD, LPOVERLAPPED), and was able to read the port fine. Noted you will need to create a DCB struct to use this method. Either way is better than the exception bubbling up to the UI, crashing the CLR, and making doody all over your client.

    From the MSDN regarding the SerialPort.DataReceived event

    "The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread."

    As far as I can tell, the only reason for the calls to SetCommMask and WaitCommEvent are for taking off a bit of CPU load and allowing the thread to block on WaitCommEvent until data is received on the internal buffer. So in other words, its not necessary for reading data from the buffer. Even if you call ReadFile and there is no data on the buffer, ReadFile will simply block until there IS data on the buffer.

    As for my using unsafe code, no... I didnt have to use it, I had to use some interop and thats what I meant. My stack pointers were being moved and I totally forgot about the "fixed" keyword. But I used fixed and that "fixed" the problem, haha.
    __________________
    R.I.P. 3.5" Floppy Drives
    "I know not with what weapons World War III will be fought, but World War IV will be fought with sticks and stones." - Albert Einstein

    Last edited by RaleTheBlade; February 3rd, 2009 at 12:40 AM. Reason: More Info
    Reply With Quote
      #9    
    Old June 16th, 2009, 10:02 PM
    Mucaro Mucaro is offline
    Junior Member
     
    Join Date: Jun 2009
    Posts: 1
    Mucaro is an unknown quantity at this point (<10)
    Thumbs up Re: UnauthorizedAccessException when accessing Virtual COM port

    Quote:
    Originally Posted by MontgomeryBurns View Post
    I solved my problem adding a config file to my Visual Studio C# project. My app.config file is this:
    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    	<runtime>
    		<legacyUnhandledExceptionPolicy enabled="true"/>
    	</runtime>
    </configuration>
    as explained here:
    http://connect.microsoft.com/VisualS...edbackID=98348

    Thanks to everybody for sharing your knowledge. MontgomeryBurns's solution fixed my problem. I wrote a GUI for a USB device that creates a virtual serial port. The GUI can detect the presence of the device and connect or reconnect automatically multiple times, but would raise the aformentioned exception upon exit.
    Reply With Quote
      #10    
    Old November 6th, 2009, 01:56 PM
    denizkartan denizkartan is offline
    Junior Member
     
    Join Date: Nov 2008
    Posts: 10
    denizkartan is an unknown quantity at this point (<10)
    Re: UnauthorizedAccessException when accessing Virtual COM port

    I have a similar problem:
    My application connects to port, then I unplug the cable. Then I plug the cable again and reconnect to the port. Everything goes fine for a while (I can close and dispose SerialPort object after the unplug and can reconnect with the same object after replugging the cable. Even funnier I even can read port and write to it after replugging!) but after some time UnauthorizedAccessException saying "Access to the port is denied" is thrown.
    I tried setting legacyUnhandledExceptionPolicy to true in the application configuration file but it didn't solve my problem.
    Any suggestions?
    Reply With Quote
      #11    
    Old November 6th, 2009, 04:21 PM
    RaleTheBlade's Avatar
    RaleTheBlade RaleTheBlade is offline
    Member
     
    Join Date: Jul 2007
    Location: Illinois
    Posts: 453
    RaleTheBlade has a spectacular aura about (150+) RaleTheBlade has a spectacular aura about (150+)
    Re: UnauthorizedAccessException when accessing Virtual COM port

    Quote:
    Originally Posted by denizkartan View Post
    I have a similar problem:
    My application connects to port, then I unplug the cable. Then I plug the cable again and reconnect to the port. Everything goes fine for a while (I can close and dispose SerialPort object after the unplug and can reconnect with the same object after replugging the cable. Even funnier I even can read port and write to it after replugging!) but after some time UnauthorizedAccessException saying "Access to the port is denied" is thrown.
    I tried setting legacyUnhandledExceptionPolicy to true in the application configuration file but it didn't solve my problem.
    Any suggestions?
    Its an exception that's thrown from within the .NET Framework and you cant handle it and keep the application running. I fixed it by using some interop with the kernel32 library. Research how to open and read/write serial ports in Win32 C++ and then call the functions from C# code using some interop.
    __________________
    R.I.P. 3.5" Floppy Drives
    "I know not with what weapons World War III will be fought, but World War IV will be fought with sticks and stones." - Albert Einstein
    Reply With Quote
      #12    
    Old December 23rd, 2009, 04:37 PM
    kingneb kingneb is offline
    Junior Member
     
    Join Date: Sep 2008
    Posts: 2
    kingneb is an unknown quantity at this point (<10)
    Re: UnauthorizedAccessException when accessing Virtual COM port

    Hello,

    I am running the .NET framework 3.5 and am having the same problem as all of you. I connect my USB cable to the PC and pull it while data is being transmitted. I have a try catch block that detects the dissapearrence of the COM port. When you reconnect it and restart the transmission I recieve the UnauthorizedAccessException. In the .NET framework 3.5 how do you prevent this or catch this one? I tried the config file but it did not work .

    Any advice?
    Reply With Quote
      #13    
    Old December 23rd, 2009, 06:03 PM
    kingneb kingneb is offline
    Junior Member
     
    Join Date: Sep 2008
    Posts: 2
    kingneb is an unknown quantity at this point (<10)
    Re: UnauthorizedAccessException when accessing Virtual COM port

    Better yet, one guy said use c++ to open the com ports. I know nothing about interops. Does this mean you can call a C++ class from C#?
    Reply With Quote
    Reply

    Bookmarks

    Tags
    usb , virtual com
    Go Back   CodeGuru Forums > .NET Programming > C-Sharp Programming


    Thread Tools Search this Thread
    Search this Thread:

    Advanced Search
    Display Modes Rate This Thread
    Rate This Thread:

    Posting Rules
    You may not post new threads
    You may not post replies
    You may not post attachments
    You may not edit your posts

    BB code is On
    Smilies are On
    [IMG] code is On
    HTML code is Off
    Forum Jump


    All times are GMT -5. The time now is 11:00 AM.



    Acceptable Use Policy


    The Network for Technology Professionals

    Search:

    About Internet.com

    Legal Notices, Licensing, Permissions, Privacy Policy.
    Advertise | Newsletters | E-mail Offers


    Powered by vBulletin® Version 3.7.3
    Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.