Rick Strahl's Web Log

Wind, waves, code and everything in between...
ASP.NET • C# • HTML5 • JavaScript • AngularJs
Contact   •   Articles   •   Products   •   Support   •   Search
Ad-free experience sponsored by:
ASPOSE - the market leader of .NET and Java APIs for file formats – natively work with DOCX, XLSX, PPT, PDF, images and more

C# HRESULT comparison


:P
On this page:

I just had a little brain freeze dealing with an HRESULT error from a COMException. When dealing with COM objects you still need to deal with the unfortunate COM idiosyncrasies like HRESULT values which get returned from just about every COM call.

COMException exposes this HRESULT as an int value in the Exception's ErrorCode property. Now in my brain freeze haze I tried something like this:

try
{
    this.OutputBuffer = this.ComInstance.GetType().InvokeMember("ProcessHit", BindingFlags.InvokeMethod,
                                                                null, this.ComInstance, 
                                                                new object[1] { this.CompleteInputBuffer }) as string;
}
catch (COMException ex)
{
    // *** RPC Server Unavailable 
    if ( ex.ErrorCode == 0x800706ba ) 
    {
        // try to reload the server
        if (this.LoadServer())
            return this.CallComServer();
    }
    this.ErrorMessage = ex.Message;
    return false;
}
catch (Exception ex)
{
    this.ErrorMessage = ex.Message;
    return false;
}
finally
{
    this.EndRequest();
}

Now that seems like it should work well enough right? 

Eh, not quite. The problem is that the constant hex value is created as a uint while the HRESULT is a signed integer. The code compiles just fine but at runtime the comparision may fail (depending on the HRESULT's actual value - high values like the one above (and aren't just about all COM errors 0x800... <s>) will fail.

So quick - how do  you create a signed hex constant?

I don't know, but this works as expected:

if ( (uint) ex.ErrorCode == 0x800706ba ) 

Hopefully this will save somebody the 15 minutes I just wasted on this <s>...

Posted in .NET  COM  

The Voices of Reason


 

Evan
June 20, 2007

# re: C# HRESULT comparison

Thanks!! You just saved me 15 minutes as well!!!

Tom
August 29, 2007

# re: C# HRESULT comparison

You saved me some time too- thanks!

Matt
May 06, 2008

# re: C# HRESULT comparison

Another 15 minutes saved. That's a grand total of 45 minutes now :)

Will
April 28, 2009

# re: C# HRESULT comparison

Thanks a lot... You also saved me some time. :)

Markus
April 20, 2011

# re: C# HRESULT comparison

if ( (uint) ex.ErrorCode == 0x800706ba )


this will not work. throws an OverflowException, depending on the value of ex.ErrorCode (at least it did in my case).

to prevent the runtime from doing the overflow-check when casting, do this:
if ( unchecked ( (uint) ex.ErrorCode ) == 0x800706ba )

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2019