Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'System.Exception.HResult' is inaccessible due to its protection level

Tags:

c#

asp.net

I am getting the the following error in my code.

Compiler Error Message: CS0122: 'System.Exception.HResult' is inaccessible due to its protection level

I have one class in my App_Code folder and using LogException() method of that class to insert exception details to database.

Business access layer reference is already given to this class for accessing functionality.

I tried it in in my local machine and local IIS, it is working fine. but when i am hosting it on windows server IIS then it is giving me error.

Please help me to solve this problem.

Updated:

Below is my function in App_Code/Exception.cs class and I referenced the Business Access Layer in this class.

public static void LogException(Exception ex, string userId, string refPage, string appName)
{
    try
    {
        ExceptionManager objEx = new ExceptionManager(); // this is business class
        objEx.InsertErrorLog(userId, appName, ex.HResult, ex.GetHashCode(), ex.GetType().ToString(), ex.Message, ex.Source, ex.StackTrace, refPage);
    }
    catch {
        DestroySession();
    }
}
like image 643
Chirag Avatar asked Jan 13 '23 03:01

Chirag


2 Answers

Update to .NET 4.5.

Or call System.Runtime.InteropServices.Marshal.GetHRForException.

The code from the original post, with this change:

public static void LogException(Exception ex, string userId, string refPage, string appName)
{
    try
    {
        ExceptionManager objEx = new ExceptionManager(); // this is business class
        objEx.InsertErrorLog(userId, appName,
                System.Runtime.InteropServices.Marshal.GetHRForException(ex),
                ex.GetHashCode(), ex.GetType().ToString(), ex.Message, ex.Source, ex.StackTrace, refPage);
    }
    catch {
        DestroySession();
    }
}
like image 174
Dan Korn Avatar answered Jan 30 '23 21:01

Dan Korn


Sounds like you are trying to set the HResult property of the Exception. You can't do this as it's setter is protected. If you need to set this property then your only alternative is to derive a new type of Exception e.g.

public class CustomException : Exception
{
    public CustomException(string message, int hresult)
        : base(message)
    {
        HResult = hresult
    }
}

Seems to me your actual issue is a difference in .NET versions between your dev / deployment environments. The HResult property was completely protected up until 4.5. The reason you are seeing this once deployed, I assume, is because you are running under an older version of .NET.

You will need to install .NET 4.5 on your deployment machine.

like image 28
James Avatar answered Jan 30 '23 19:01

James