Friday, December 2, 2011

System.UnauthorizedAccessException: Access to the port is denied

This exception can occur in an application that is communicating with a USB device via a System.IO.Ports.SerialPort object. If the USB cable is unplugged before SerialPort.Close() is called, this unhandled exception will be thrown and cannot be caught. Ultimately, the application will crash. This issue has been reported to Microsoft here.

There are three possible ways to resolve this issue:
  1. Step up to .NET Framework 4 where this issue no longer occurs.

  2. Use the workaround supplied by Microsoft:

    Revert to the .NET Framework 1.1 behavior and catch the exception. To do this, set the legacyUnhandledExceptionPolicy in the application config file, as in the following example:

    <configuration>
      <runtime> 
        <legacyUnhandledExceptionPolicy enabled="1"/>
      </runtime>
    </configuration>

  3. Solution #2 does not apply to .NET Framework 3.5. While it does prevent the application from crashing, the exception still cannot be caught. In this case, suppress the finalization of the SerialPort BaseStream, as in the following example:

    SerialPort _SerialPort;
    Stream
    _SafeBaseStream;

    public
    void Open()
    {
       
        _SerialPort.Open();
       
        _SafeBaseStream = _SerialPort.BaseStream;

    }


    public
    void Close()
    {
        if
    (_SerialPort.IsOpen)
            _SerialPort.Close();
        else
            GC.SuppressFinalize(_SafeBaseStream);

        _SerialPort = null;
        _SafeBaseStream = null;
    }

    Just note that using this may result in BaseStream leaking resources.

Wednesday, September 7, 2011

App.config is inaccessible from unit test project

By default, in Visual Studio Team Test, a project’s App.config is not accessible from the unit test project. If you need access to it from your unit test, you can include a post-build event to rename it and add it to your unit test output directory. Follow these steps:

1.       Right click on the unit test project
2.       Select “Properties”
3.       Select the “Build Events” tab
4.       In the “Post-build event command line” text box, enter:

copy "<project path>App.config" "$(ProjectDir)$(OutDir)$(TargetFileName).config"

Where <project path> is the path to the location of the App.config. This can be a relative path such as:

copy "$(ProjectDir)../MyProject/App.config" "$(ProjectDir)$(OutDir)$(TargetFileName).config"
5.       Save  ­­  

Tuesday, July 12, 2011

Difference between Application.Exit() and standard Close (X) button

While both Application.Exit() and the close button both terminate an application, it is still possible that they result in different behavior. The key difference is that the Application.Exit() method does not raise the Form.Closed or Form.Closing events, while the Form.Close() method does. Pressing the standard Close(X) button is equivalent to Form.Close().

The Form.Closed and Form.Closing events are obsolete since .NET 2.0. Instead, the Form.FormClosed and Form.FormClosing events should be used, which are raised by both Application.Exit() and the Form.Close() method.

The following code demonstrates these differences:

public partial class TestForm : Form
{
    public TestForm()
    {
        InitializeComponent();

        Closed += new EventHandler(TestForm_Closed);
        Closing += new CancelEventHandler(TestForm_Closing);

        FormClosed += new System.Windows.Forms.FormClosedEventHandler(TestForm_FormClosed);
        FormClosing += new System.Windows.Forms.FormClosingEventHandler(TestForm_FormClosing);

        exitButton.Click += new System.EventHandler(exitButton_Click);
        closeButton.Click += new System.EventHandler(closeButton_Click);
    }

    private void TestForm_Closed(object sender, EventArgs e)
    {
        MessageBox.Show("Form.Closed event raised by Form.Close() method.");
    }

    private void TestForm_Closing(object sender, CancelEventArgs e)
    {
        MessageBox.Show("Form.Closing event raised by Form.Close() method.");
    }

    private void TestForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        MessageBox.Show("Form.FormClosed event raised by Form.Close() or Application.Exit() methods.");
    }

    private void TestForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        MessageBox.Show("Form.FormClosing event raised by Form.Close() or Application.Exit() methods.");
    }

    private void exitButton_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void closeButton_Click(object sender, EventArgs e)
    {
        Close();
    }
}

Saturday, June 25, 2011

Unit tests fail after enabling Code Coverage

If you add an assembly for code coverage analysis and your unit tests start to fail, then it is probably caused by the following exception:

System.Security.SecurityException: Strong name validation failed.

To fix this issue, in Visual Studio, do the following:
  1. Select “Test” > “Edit Test Run Configurations”
  2. Choose the appropriate testrunconfig
  3. Select the “Code Coverage” section.
  4.  Make sure the “Re-signing key file” is populated with the key file used to sign your assembly.

Tuesday, June 7, 2011

Autoformatting an Entire File or Selection in Visual Studio

Have you ever copied and pasted some code from the Internet or maintained legacy code that was poorly formatted? Luckily, Visual Studio has some shortcuts to easily fix the formatting.

To auto format the entire document, press Ctrl + K, Ctrl + D
To auto format a selection or a the current line, press Ctrl + K, Ctrl + F  

Wednesday, May 25, 2011

Difference Between \n, \r, and Environment.NewLine

\n 
  • CR (Carriage Return)
  • Same as (char)13
  • Used as a new line character in Unix
\r
  • LF (Line Feed)
  • Used as a new line character in Mac OS
\n\r
  • CR + LF (Carriage Return + Line Feed)
  • Used as a new line character in Windows
Environment.NewLine
  • Any of the above codes, based on the Operating System
  • This is the preferred method


Monday, May 16, 2011

Formatting the Same Line of Text with Different Word Styles

I was having an issue applying multiple Microsoft Word styles to the same line of text using the Word Interop. Each time I set a style to a substring, Word would apply that style to the entire line of text.

This was happening because the “Style type” was “Paragraph”. Therefore, whenever I set the style to one part of the paragraph, it would apply it to the entire paragraph. To fix this problem, I changed the style type to “Character”.  This allowed me to format a line with multiple styles, as long as each style was a “Character” style type.

If you are curious, below is the C# code I used to add the formatted text:

public void AddFormattedText(
    Word.Range range, string text, string style)
{
    object refStyle = style;

    // Get position to start formatting
    // (before inserting text)
    int startFormat = range.End;

    // Insert the text
    range.InsertAfter(text);

    // Get position to end formatting
    // (after inserting text)
    int endFormat = range.End;

    // Create a new range between the
    // start and end positions
    Word.Range formatMe = range;
    formatMe.SetRange(startFormat, endFormat);

    // Format the range between the
    // start and end positions
    formatMe.set_Style(ref refStyle);
}