Inheritance: ExternalException
Beispiel #1
0
        public static string GetErrorMessage(COMException ce)
        {
            //These error messages come from the WIA documenation.
            if (ce.ErrorCode == WIA_ERROR_GENERAL_ERROR) { return "An unknown error has occurred with the Windows Image Acquisition (WIA) device."; }
            if (ce.ErrorCode == WIA_ERROR_PAPER_JAM) { return "Paper is jammed in the scanner's document feeder."; }
            if (ce.ErrorCode == WIA_ERROR_PAPER_EMPTY) { return "The user requested a scan and there are no documents left in the document feeder."; }
            if (ce.ErrorCode == WIA_ERROR_PAPER_PROBLEM) { return "An unspecified problem occurred with the scanner's document feeder."; }
            if (ce.ErrorCode == WIA_ERROR_OFFLINE) { return "The WIA device is not online."; }
            if (ce.ErrorCode == WIA_ERROR_BUSY) { return "The WIA device is busy."; }
            if (ce.ErrorCode == WIA_ERROR_WARMING_UP) { return "The WIA device is warming up."; }
            if (ce.ErrorCode == WIA_ERROR_USER_INTERVENTION) { return "An unspecified error has occurred with the WIA device that requires user intervention. The user should ensure that the device is turned on, online, and any cables are properly connected."; }
            if (ce.ErrorCode == WIA_ERROR_ITEM_DELETED) { return "The WIA device was deleted. It can no longer be accessed."; }
            if (ce.ErrorCode == WIA_ERROR_DEVICE_COMMUNICATION) { return "	An unspecified error occurred during an attempted communication with the WIA device."; }
            if (ce.ErrorCode == WIA_ERROR_INVALID_COMMAND) { return "	The device does not support this command."; }
            if (ce.ErrorCode == WIA_ERROR_INCORRECT_HARDWARE_SETTING) { return "There is an incorrect setting on the WIA device."; }
            if (ce.ErrorCode == WIA_ERROR_DEVICE_LOCKED) { return "The scanner head is locked."; }
            if (ce.ErrorCode == WIA_ERROR_EXCEPTION_IN_DRIVER) { return "The device driver threw an exception."; }
            if (ce.ErrorCode == WIA_ERROR_INVALID_DRIVER_RESPONSE) { return "The response from the driver is invalid."; }
            if (ce.ErrorCode == WIA_S_NO_DEVICE_AVAILABLE) { return "No WIA device of the selected type is available."; }

            //These error messages are totally made up because they don't appear in the
            //documentation but are defined in WiaDef.h
            if (ce.ErrorCode == WIA_ERROR_COVER_OPEN) { return "The device cover is open."; }
            if (ce.ErrorCode == WIA_ERROR_LAMP_OFF) { return "The devices lamp is off."; }
            if (ce.ErrorCode == WIA_ERROR_DESTINATION) { return "The destination is invalid"; }
            if (ce.ErrorCode == WIA_ERROR_NETWORK_RESERVATION_FAILED) { return "A network error occurred."; }
            if (ce.ErrorCode == WIA_STATUS_END_OF_MEDIA) { return "End of media reached."; }

            //Watch for the specific error that means that the Wia Automation library is not installed.
            if (ce.ErrorCode == COM_ERROR_CLASS_NOT_REGISTERED) { return ce.Message + "\r\nEnsure that the WIA Automation Library 2.0 is installed and registered."; }

            //If it's not a WIA error then just return the message we got from COM.
            return ce.Message;
        }
        private static bool ConvertException(COMException e, out Exception uiaException)
        {
            bool handled = true;
            switch (e.ErrorCode)
            {
                case UIA_E_ELEMENTNOTAVAILABLE:
                    uiaException = new ElementNotAvailableException(e);
                    break;

                case UIA_E_ELEMENTNOTENABLED:
                    uiaException = new ElementNotEnabledException(e);
                    break;

                case UIA_E_NOCLICKABLEPOINT:
                    uiaException = new NoClickablePointException(e);
                    break;

                case UIA_E_PROXYASSEMBLYNOTLOADED:
                    uiaException = new ProxyAssemblyNotLoadedException(e);
                    break;

                default:
                    uiaException = null;
                    handled = false;
                    break;
            }
            return handled;
        }
Beispiel #3
0
        static public IntPtr CreateClass(Guid rclsid, Guid riid)
        {
            IntPtr classFactory;
            IntPtr objCreatedObject;

            COMException Exception;
            // Create a local copy so that we can pass it's reference
            Guid IClassFactory = IID_IClassFactory;
            int hr;
            hr = DllGetClassObject(ref rclsid, ref IClassFactory, out classFactory);
            try
            {
                if (hr < 0)
                {
                    Exception = new COMException("Call to DllGetClassObject failed.", hr);
                    throw Exception;
                }
                hr = ClassFactory_CreateInstance(classFactory, ref riid, out objCreatedObject);
                if (hr < 0)
                {
                    Exception = new COMException("Call to CreateInstance failed.", hr);
                    throw Exception;
                }
            }
            finally
            {
                ClassFactory_Release(classFactory);
            }

            return objCreatedObject;
        }
Beispiel #4
0
 public HttpException(HttpResponseMessage response, COMException innerException, string message = null)
     : this(GetResponseExceptionMessage(response, message), innerException)
 {
     HResult = innerException.HResult;
     _request = response?.RequestMessage;
     _response = response;
 }
Beispiel #5
0
 // Helper funciton.
 static void ReportCOMError(COMException e)
 {
     Console.WriteLine("*************************************");
     Console.WriteLine("Raw HRESULT: {0}", e.ErrorCode);
     Console.WriteLine("Message: {0}", e.Message);
     Console.WriteLine("Source of error: {0}", e.Source);
     Console.WriteLine("Method Name: {0}", e.TargetSite);
     Console.WriteLine("*************************************\n");
 }
 /// <summary>
 /// Creates a new UPnPException.
 /// </summary>
 /// <param name="comException">The underlying COM Exception.</param>
 public UPnPException(COMException comException)
     : base(String.Format(
             "UPnP Error #{0}: {1}", 
             comException.ErrorCode, 
             ((UPnPErrorCode)(comException.ErrorCode)).ToString()), 
         comException)
 {
     mecCode = (UPnPErrorCode)(comException.ErrorCode);
 }
Beispiel #7
0
 public SDKConnectionException(COMException cex)
     : base(cex)
 {
     switch ((uint)cex.ErrorCode)
     {
         default:
             ProblemDetail = String.Format("{0}, Code: {1:X}", cex.Message, cex.ErrorCode);
             break;
     }
 }
 internal static Exception CreateFormattedComException(COMException e)
 {
     StringBuilder errorBuffer = new StringBuilder(0x100);
     StringBuilder nameBuffer = new StringBuilder();
     int error = 0;
     SafeNativeMethods.ADsGetLastError(out error, errorBuffer, 0x100, nameBuffer, 0);
     if (error != 0)
     {
         return new DirectoryServicesCOMException(errorBuffer.ToString(), error, e);
     }
     return e;
 }
Beispiel #9
0
        /// <summary>
        /// Converts a System.Runtime.InteropServices.COMException into more meaningful ICF exception (e.g. AlreadyExistsException).
        /// </summary>
        ///
        /// Actually, it is questionable if the exception mapping can be done in a universal way like this,
        /// or whether it has to be specific for individual operations (search, create, update, ...). We
        /// will see.
        public static Exception OtherComToIcfException(System.Runtime.InteropServices.COMException originalException, String message)
        {
            LOGGER.TraceEvent(TraceEventType.Information, CAT_DEFAULT, "ErrorCode = {0}", originalException.ErrorCode);

            if (originalException.ErrorCode == -2147022651)                                                   // password too weak
            {
                return(new ArgumentException(originalException.Message + ": " + message, originalException)); /* see also https://groups.google.com/d/msg/connid-dev/i4-N22CARZ8/S-1Yv-iqWBUJ */
            }
            else
            {
                return(originalException);
            }
        }
        internal static Exception CreateFormattedComException(COMException e)
        {
            // get extended error information
            StringBuilder errorBuffer = new StringBuilder(256);
            StringBuilder nameBuffer = new StringBuilder();
            int error = 0;
            SafeNativeMethods.ADsGetLastError(out error, errorBuffer, 256, nameBuffer, 0);

            if (error != 0)
                return new DirectoryServicesCOMException(errorBuffer.ToString(), error, e);
            else
                return e;
        }
Beispiel #11
0
        public static void ThrowExceptionForHR(int hr)
        {
            if (hr < 0)
            {
                string s = GetErrorText(hr);
                COMException ex = null;
                
                if (string.IsNullOrEmpty(s))
                    ex = new COMException("COM Error", hr);
                else
                    ex = new COMException(s, hr);

                throw ex;
            }
        }
Beispiel #12
0
 private Office.CustomTaskPane CreateCTP(string fullName, string title)
 {
     Office.CustomTaskPane taskPane = null;
     try
     {
         taskPane = TaskPaneFactory.CreateCTP(fullName, title) as Office.CustomTaskPane;
     }
     catch (NetRuntimeSystem.Exception exception)
     {
         string message = String.Format("Unable to create {0}({1}).", fullName, title);
         NetRuntimeSystem.Runtime.InteropServices.COMException wrapperException = new NetRuntimeSystem.Runtime.InteropServices.COMException(message, exception);
         Factory.Console.WriteException(wrapperException);
         OnError(ErrorMethodKind.CTPFactoryAvailable, wrapperException);
     }
     return(taskPane);
 }
Beispiel #13
0
        public static void ValidateExceptionForHRAPI()
        {
            int          errorCode      = -2146231029;
            COMException getHRException = Marshal.GetExceptionForHR(errorCode) as COMException;

            Assert.NotNull(getHRException);
            Assert.Equal(errorCode, getHRException.HResult);
            try
            {
                Marshal.ThrowExceptionForHR(errorCode);
            }
            catch (COMException e)
            {
                Assert.Equal(errorCode, e.HResult);
                Assert.Equal(e.HResult, getHRException.HResult);
            }
        }
Beispiel #14
0
        public static void LoadActiveDirectory()
        {
            try
            {
                // Bind to the users container.
                _searchRoot = new DirectoryEntry(string.Format("LDAP://{0}/{1}", Storage.Domain, Storage.Container), Storage.User, Storage.Password);
                // Create a DirectorySearcher object.
                _mySearcher = new DirectorySearcher(_searchRoot, "(objectClass=user)");
                _mySearcher.CacheResults = true;
                // Create a SearchResultCollection object to hold a collection of SearchResults
                // returned by the FindAll method.
                // _mySearcher.Filter =
                _result = _mySearcher.FindAll();
                // Get search results. For more information, see Getting Search Results.
                // ...
                // This sample uses Try...Catch to catch errors.
                // Create an Exception object. For more information, see System.Exception.
                foreach (SearchResult searchResult in _result)
                {
                    var username = searchResult.Properties["cn"];
                    var sid      = searchResult.Properties["objectsid"].ToString();
                    var user     = username[0];

                    int i = 1;
                }
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                System.Runtime.InteropServices.COMException exception =
                    new System.Runtime.InteropServices.COMException();
                Console.WriteLine(exception);
            }
            catch (InvalidOperationException)
            {
                InvalidOperationException InvOpEx = new InvalidOperationException();
                Console.WriteLine(InvOpEx.Message);
            }
            catch (NotSupportedException)
            {
                NotSupportedException NotSuppEx = new NotSupportedException();
                Console.WriteLine(NotSuppEx.Message);
            }
        }
Beispiel #15
0
        internal Exception GetException()
        {
            Debug.Assert(_pfnDeferredFillIn == IntPtr.Zero);
#if DEBUG
            System.Diagnostics.Debug.Assert(_wReserved != -1);
            _wReserved = -1; // to ensure that the method gets called only once
#endif

            int errorCode = (_scode != 0) ? _scode : _wCode;
            Exception exception = Marshal.GetExceptionForHR(errorCode);

            string message = ConvertAndFreeBstr(ref _bstrDescription);
            if (message != null)
            {
                // If we have a custom message, create a new Exception object with the message set correctly.
                // We need to create a new object because "exception.Message" is a read-only property.
                if (exception is COMException)
                {
                    exception = new COMException(message, errorCode);
                }
                else
                {
                    Type exceptionType = exception.GetType();
                    ConstructorInfo ctor = exceptionType.GetConstructor(new Type[] { typeof(string) });
                    if (ctor != null)
                    {
                        exception = (Exception)ctor.Invoke(new object[] { message });
                    }
                }
            }

            exception.Source = ConvertAndFreeBstr(ref _bstrSource);

            string helpLink = ConvertAndFreeBstr(ref _bstrHelpFile);
            if (helpLink != null && _dwHelpContext != 0)
            {
                helpLink += "#" + _dwHelpContext;
            }
            exception.HelpLink = helpLink;

            return exception;
        }
Beispiel #16
0
        /// <summary>
        /// Tries to convert a com exception to a more usable exception.
        /// </summary>
        public static bool ConvertException(System.Runtime.InteropServices.COMException ex, out Exception uiaException)
        {
            var handled = true;

            switch ((uint)ex.ErrorCode)
            {
            case UIA_E_ELEMENTNOTENABLED:
                uiaException = new ElementNotEnabledException(ex);
                break;

            case UIA_E_ELEMENTNOTAVAILABLE:
                uiaException = new ElementNotAvailableException(ex);
                break;

            case UIA_E_NOCLICKABLEPOINT:
                uiaException = new NoClickablePointException(ex);
                break;

            case UIA_E_PROXYASSEMBLYNOTLOADED:
                uiaException = new ProxyAssemblyNotLoadedException(ex);
                break;

            case UIA_E_TIMEOUT:
                uiaException = new TimeoutException("UIA Timeout", ex);
                break;

            case UIA_E_NOTSUPPORTED:
                uiaException = new Exceptions.NotSupportedException(ex);
                break;

            case UIA_E_INVALIDOPERATION:
                uiaException = new InvalidOperationException("UIA Invalid Operation", ex);
                break;

            default:
                uiaException = null;
                handled      = false;
                break;
            }
            return(handled);
        }
Beispiel #17
0
        private static void currentDomain_ThreadException(object sender, ThreadExceptionEventArgs t)
        {
            System.Runtime.InteropServices.COMException comEx = t.Exception as System.Runtime.InteropServices.COMException;

            if (comEx != null)
            {
                // RPC server fault.
                if (comEx.ErrorCode == -2147417851 || comEx.ErrorCode == -2147023174)
                {
                    // Connection
                    HandleConnectionLost();
                    return;
                }
            }

            formErrorMessage dialog = new formErrorMessage(t);

            dialog.ShowDialog();

            Instances.MainForm.Repaint();
        }
Beispiel #18
0
 MultiRecordReadAsync(
     KTL_LOG_ASN Asn,
     UInt32 BytesToRead,
     CancellationToken Token)
 {
     if (this._NativeStream2 != null)
     {
         return(Utility.WrapNativeAsyncInvokeInMTA <PhysicalLogStreamReadResults>(
                    (Callback) => this.MultiRecordReadBeginWrapper(Asn, BytesToRead, Callback),
                    (Context) => this.MultiRecordReadEndWrapper(Context),
                    Token,
                    "NativeLog.MultiRecordRead"));
     }
     else
     {
         //
         // Throw same exception that would be thrown if driver doesn't have the api
         //
         var innerException = new System.Runtime.InteropServices.COMException();
         throw new System.Fabric.FabricException("", innerException);
     }
 }
Beispiel #19
0
        public SDKSessionException(COMException cex)
            : base(cex)
        {
            switch ((uint)cex.ErrorCode)
            {
                    //Possible enhancements: Handle connection failure for online edition
                    //also we need to support the case where a company file has been specified
                    //perhaps a special callback for customizing this message?
                case 0x80040408: //old school: could not start QuickBooks
                case 0x80040416: //specify co file if not running
                case 0x80040417: //specify co file if no file open
                    ProblemDetail = "Can't connect to QuickBooks.  Please make sure:"
                        + Environment.NewLine + "1. QuickBooks is running"
                        + Environment.NewLine + "2. If QuickBooks is running, check for an application authorization dialog"
                        + Environment.NewLine + "3. If using Vista or Windows 7, make sure UAC is enabled";
                    break;

                default:
                    //it's only necessary to override the default message if we have something to say
                    ProblemDetail = String.Format("{0}, Code: {1:X}", cex.Message, cex.ErrorCode);
                    break;
            }
        }
Beispiel #20
0
        // public static uint ERROR_LDAP_INVALID_CREDENTIALS = 49; //fix error CS0414: Warning as Error: is assigned but its value is never used
        //
        // This method maps some common COM Hresults to
        // existing clr exceptions
        //

        internal static Exception GetExceptionFromCOMException(COMException e)
        {
            Exception exception;
            int errorCode = e.ErrorCode;
            string errorMessage = e.Message;

            //
            // Check if we can throw a more specific exception
            //
            if (errorCode == unchecked((int)0x80070005))
            {
                //
                // Access Denied
                //
                exception = new UnauthorizedAccessException(errorMessage, e);
            }
            else if (errorCode == unchecked((int)0x800708c5) || errorCode == unchecked((int)0x80070056) || errorCode == unchecked((int)0x8007052))
            {
                //
                // Password does not meet complexity requirements or old password does not match or policy restriction has been enforced.
                //
                exception = new PasswordException(errorMessage, e);
            }
            else if (errorCode == unchecked((int)0x800708b0) || errorCode == unchecked((int)0x80071392))
            {
                //
                // Principal already exists
                //
                exception = new PrincipalExistsException(errorMessage, e);
            }
            else if (errorCode == unchecked((int)0x8007052e))
            {
                //
                // Logon Failure
                //
                exception = new AuthenticationException(errorMessage, e);
            }
            else if (errorCode == unchecked((int)0x8007202f))
            {
                //
                // Constraint Violation
                //
                exception = new InvalidOperationException(errorMessage, e);
            }
            else if (errorCode == unchecked((int)0x80072035))
            {
                //
                // Unwilling to perform
                //
                exception = new InvalidOperationException(errorMessage, e);
            }
            else if (errorCode == unchecked((int)0x80070008))
            {
                //
                // No Memory
                //
                exception = new OutOfMemoryException();
            }
            else if ((errorCode == unchecked((int)0x8007203a)) || (errorCode == unchecked((int)0x8007200e)) || (errorCode == unchecked((int)0x8007200f)))
            {
                exception = new PrincipalServerDownException(errorMessage, e, errorCode, null);
            }
            else
            {
                //
                // Wrap the exception in a generic OperationException
                //
                exception = new PrincipalOperationException(errorMessage, e, errorCode);
            }

            return exception;
        }
 internal static void ProxyException(COMException comException)
 {
     if ((System.Transactions.Oletx.NativeMethods.XACT_E_CONNECTION_DOWN == comException.ErrorCode) || (System.Transactions.Oletx.NativeMethods.XACT_E_TMNOTAVAILABLE == comException.ErrorCode))
     {
         throw TransactionManagerCommunicationException.Create(System.Transactions.SR.GetString("TraceSourceOletx"), System.Transactions.SR.GetString("TransactionManagerCommunicationException"), comException);
     }
     if (System.Transactions.Oletx.NativeMethods.XACT_E_NETWORK_TX_DISABLED == comException.ErrorCode)
     {
         throw TransactionManagerCommunicationException.Create(System.Transactions.SR.GetString("TraceSourceOletx"), System.Transactions.SR.GetString("NetworkTransactionsDisabled"), comException);
     }
     if ((System.Transactions.Oletx.NativeMethods.XACT_E_FIRST <= comException.ErrorCode) && (System.Transactions.Oletx.NativeMethods.XACT_E_LAST >= comException.ErrorCode))
     {
         if (System.Transactions.Oletx.NativeMethods.XACT_E_NOTRANSACTION == comException.ErrorCode)
         {
             throw TransactionException.Create(System.Transactions.SR.GetString("TraceSourceOletx"), System.Transactions.SR.GetString("TransactionAlreadyOver"), comException);
         }
         throw TransactionException.Create(System.Transactions.SR.GetString("TraceSourceOletx"), comException.Message, comException);
     }
 }
Beispiel #22
0
        /// <summary>
        /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException.
        /// and in winrt and marshal APIs as Exception.
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        /// <param name="createCOMException"></param>
        /// <returns></returns>
        internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo)
        {
            if (errorCode >= 0)
            {
                return null;
            }

            Exception exception = null;

            bool shouldDisplayHR = false;

            switch (errorCode)
            {
                case __HResults.COR_E_NOTFINITENUMBER: // NotFiniteNumberException
                case __HResults.COR_E_ARITHMETIC:
                    exception = new ArithmeticException();
                    break;
                case __HResults.COR_E_ARGUMENT:
                case unchecked((int)0x800A01C1):
                case unchecked((int)0x800A01C2):
                case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT:
                    exception = new ArgumentException();

                    if (errorCode != __HResults.COR_E_ARGUMENT)
                        shouldDisplayHR = true;

                    break;
                case __HResults.E_BOUNDS:
                case __HResults.COR_E_ARGUMENTOUTOFRANGE:
                case __HResults.ERROR_NO_UNICODE_TRANSLATION:
                    exception = new ArgumentOutOfRangeException();

                    if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_ARRAYTYPEMISMATCH:
                    exception = new ArrayTypeMismatchException();
                    break;
                case __HResults.COR_E_BADIMAGEFORMAT:
                case __HResults.CLDB_E_FILE_OLDVER:
                case __HResults.CLDB_E_INDEX_NOTFOUND:
                case __HResults.CLDB_E_FILE_CORRUPT:
                case __HResults.COR_E_NEWER_RUNTIME:
                case __HResults.COR_E_ASSEMBLYEXPECTED:
                case __HResults.ERROR_BAD_EXE_FORMAT:
                case __HResults.ERROR_EXE_MARKED_INVALID:
                case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT:
                case __HResults.ERROR_NOACCESS:
                case __HResults.ERROR_INVALID_ORDINAL:
                case __HResults.ERROR_INVALID_DLL:
                case __HResults.ERROR_FILE_CORRUPT:
                case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY:
                case __HResults.META_E_BAD_SIGNATURE:
                    exception = new BadImageFormatException();

                    // Always show HR for BadImageFormatException
                    shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT:
                    exception = new FormatException();
                    break; // CustomAttributeFormatException
                case __HResults.COR_E_DATAMISALIGNED:
                    exception = InteropExtensions.CreateDataMisalignedException(message); // TODO: Do we need to add msg here?
                    break;
                case __HResults.COR_E_DIVIDEBYZERO:
                case __HResults.CTL_E_DIVISIONBYZERO:
                    exception = new DivideByZeroException();

                    if (errorCode != __HResults.COR_E_DIVIDEBYZERO)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_DLLNOTFOUND:
#if ENABLE_WINRT
                    exception = new DllNotFoundException();
#endif
                    break;
                case __HResults.COR_E_DUPLICATEWAITOBJECT:
                    exception = new ArgumentException();
                    break; // DuplicateWaitObjectException
                case __HResults.COR_E_ENDOFSTREAM:
                case unchecked((int)0x800A003E):
                    exception = new System.IO.EndOfStreamException();

                    if (errorCode != __HResults.COR_E_ENDOFSTREAM)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_TYPEACCESS: // TypeAccessException
                case __HResults.COR_E_ENTRYPOINTNOTFOUND:
                    exception = new TypeLoadException();

                    break; // EntryPointNotFoundException
                case __HResults.COR_E_EXCEPTION:
                    exception = new Exception();
                    break;
                case __HResults.COR_E_DIRECTORYNOTFOUND:
                case __HResults.STG_E_PATHNOTFOUND:
                case __HResults.CTL_E_PATHNOTFOUND:
                    exception = new System.IO.DirectoryNotFoundException();

                    if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_FILELOAD:
                case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION:
                case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED:
                case __HResults.FUSION_E_LOADFROM_BLOCKED:
                case __HResults.FUSION_E_CACHEFILE_FAILED:
                case __HResults.FUSION_E_ASM_MODULE_MISSING:
                case __HResults.FUSION_E_INVALID_NAME:
                case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED:
                case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH:
                case __HResults.COR_E_MODULE_HASH_CHECK_FAILED:
                case __HResults.FUSION_E_REF_DEF_MISMATCH:
                case __HResults.SECURITY_E_INCOMPATIBLE_SHARE:
                case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE:
                case __HResults.SECURITY_E_UNVERIFIABLE:
                case __HResults.COR_E_FIXUPSINEXE:
                case __HResults.ERROR_TOO_MANY_OPEN_FILES:
                case __HResults.ERROR_SHARING_VIOLATION:
                case __HResults.ERROR_LOCK_VIOLATION:
                case __HResults.ERROR_OPEN_FAILED:
                case __HResults.ERROR_DISK_CORRUPT:
                case __HResults.ERROR_UNRECOGNIZED_VOLUME:
                case __HResults.ERROR_DLL_INIT_FAILED:
                case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED:
                case __HResults.CORSEC_E_MISSING_STRONGNAME:
                case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS:
                case __HResults.ERROR_FILE_INVALID:
                    exception = new System.IO.FileLoadException();

                    shouldDisplayHR = true;
                    break;
                case __HResults.COR_E_PATHTOOLONG:
                    exception = new System.IO.PathTooLongException();
                    break;
                case __HResults.COR_E_IO:
                case __HResults.CTL_E_DEVICEIOERROR:
                case unchecked((int)0x800A793C):
                case unchecked((int)0x800A793D):
                    exception = new System.IO.IOException();

                    if (errorCode != __HResults.COR_E_IO)
                        shouldDisplayHR = true;

                    break;
                case __HResults.ERROR_FILE_NOT_FOUND:
                case __HResults.ERROR_MOD_NOT_FOUND:
                case __HResults.ERROR_INVALID_NAME:
                case __HResults.CTL_E_FILENOTFOUND:
                case __HResults.ERROR_BAD_NET_NAME:
                case __HResults.ERROR_BAD_NETPATH:
                case __HResults.ERROR_NOT_READY:
                case __HResults.ERROR_WRONG_TARGET_NAME:
                case __HResults.INET_E_UNKNOWN_PROTOCOL:
                case __HResults.INET_E_CONNECTION_TIMEOUT:
                case __HResults.INET_E_CANNOT_CONNECT:
                case __HResults.INET_E_RESOURCE_NOT_FOUND:
                case __HResults.INET_E_OBJECT_NOT_FOUND:
                case __HResults.INET_E_DOWNLOAD_FAILURE:
                case __HResults.INET_E_DATA_NOT_AVAILABLE:
                case __HResults.ERROR_DLL_NOT_FOUND:
                case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW:
                case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH:
                case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND:
                    exception = new System.IO.FileNotFoundException();

                    shouldDisplayHR = true;
                    break;
                case __HResults.COR_E_FORMAT:
                    exception = new FormatException();
                    break;
                case __HResults.COR_E_INDEXOUTOFRANGE:
                case unchecked((int)0x800a0009):
                    exception = new IndexOutOfRangeException();

                    if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_INVALIDCAST:
                    exception = new InvalidCastException();
                    break;
                case __HResults.COR_E_INVALIDCOMOBJECT:
                    exception = new InvalidComObjectException();
                    break;
                case __HResults.COR_E_INVALIDOLEVARIANTTYPE:
                    exception = new InvalidOleVariantTypeException();
                    break;
                case __HResults.COR_E_INVALIDOPERATION:
                case __HResults.E_ILLEGAL_STATE_CHANGE:
                case __HResults.E_ILLEGAL_METHOD_CALL:
                case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT:
                case __HResults.APPMODEL_ERROR_NO_PACKAGE:
                    exception = new InvalidOperationException();

                    if (errorCode != __HResults.COR_E_INVALIDOPERATION)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_MARSHALDIRECTIVE:
                    exception = new MarshalDirectiveException();
                    break;
                case __HResults.COR_E_METHODACCESS: // MethodAccessException
                case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException
                case __HResults.COR_E_FIELDACCESS:
                case __HResults.COR_E_MEMBERACCESS:
                    exception = new MemberAccessException();

                    if (errorCode != __HResults.COR_E_METHODACCESS)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_MISSINGFIELD: // MissingFieldException
                case __HResults.COR_E_MISSINGMETHOD: // MissingMethodException
                case __HResults.COR_E_MISSINGMEMBER:
                case unchecked((int)0x800A01CD):
                    exception = new MissingMemberException();
                    break;
                case __HResults.COR_E_MISSINGMANIFESTRESOURCE:
                    exception = new System.Resources.MissingManifestResourceException();
                    break;
                case __HResults.COR_E_NOTSUPPORTED:
                case unchecked((int)0x800A01B6):
                case unchecked((int)0x800A01BD):
                case unchecked((int)0x800A01CA):
                case unchecked((int)0x800A01CB):
                    exception = new NotSupportedException();

                    if (errorCode != __HResults.COR_E_NOTSUPPORTED)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_NULLREFERENCE:
                    exception = new NullReferenceException();
                    break;
                case __HResults.COR_E_OBJECTDISPOSED:
                case __HResults.RO_E_CLOSED:
                    // No default constructor
                    exception = new ObjectDisposedException(String.Empty);
                    break;
                case __HResults.COR_E_OPERATIONCANCELED:
#if ENABLE_WINRT
                    exception = new OperationCanceledException();
#endif
                    break;
                case __HResults.COR_E_OVERFLOW:
                case __HResults.CTL_E_OVERFLOW:
                    exception = new OverflowException();
                    break;
                case __HResults.COR_E_PLATFORMNOTSUPPORTED:
                    exception = new PlatformNotSupportedException(message);
                    break;
                case __HResults.COR_E_RANK:
                    exception = new RankException();
                    break;
                case __HResults.COR_E_REFLECTIONTYPELOAD:
#if ENABLE_WINRT
                    exception = new System.Reflection.ReflectionTypeLoadException(null, null);
#endif
                    break;
                case __HResults.COR_E_SECURITY:
                case __HResults.CORSEC_E_INVALID_STRONGNAME:
                case __HResults.CTL_E_PERMISSIONDENIED:
                case unchecked((int)0x800A01A3):
                case __HResults.CORSEC_E_INVALID_PUBLICKEY:
                case __HResults.CORSEC_E_SIGNATURE_MISMATCH:
                    exception = new System.Security.SecurityException();
                    break;
                case __HResults.COR_E_SAFEARRAYRANKMISMATCH:
                    exception = new SafeArrayRankMismatchException();
                    break;
                case __HResults.COR_E_SAFEARRAYTYPEMISMATCH:
                    exception = new SafeArrayTypeMismatchException();
                    break;
                case __HResults.COR_E_SERIALIZATION:
                    exception = new System.Runtime.Serialization.SerializationException(message);
                    break;
                case __HResults.COR_E_SYNCHRONIZATIONLOCK:
                    exception = new System.Threading.SynchronizationLockException();
                    break;
                case __HResults.COR_E_TARGETINVOCATION:
                    exception = new System.Reflection.TargetInvocationException(null);
                    break;
                case __HResults.COR_E_TARGETPARAMCOUNT:
                    exception = new System.Reflection.TargetParameterCountException();
                    break;
                case __HResults.COR_E_TYPEINITIALIZATION:
                    exception = InteropExtensions.CreateTypeInitializationException(message);
                    break;
                case __HResults.COR_E_TYPELOAD:
                case __HResults.RO_E_METADATA_NAME_NOT_FOUND:
                case __HResults.CLR_E_BIND_TYPE_NOT_FOUND:
                    exception = new TypeLoadException();

                    if (errorCode != __HResults.COR_E_TYPELOAD)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_UNAUTHORIZEDACCESS:
                case __HResults.CTL_E_PATHFILEACCESSERROR:
                case unchecked((int)0x800A014F):
                    exception = new UnauthorizedAccessException();

                    shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_VERIFICATION:
                    exception = new System.Security.VerificationException();
                    break;
                case __HResults.E_NOTIMPL:
                    exception = new NotImplementedException();
                    break;
                case __HResults.E_OUTOFMEMORY:
                case __HResults.CTL_E_OUTOFMEMORY:
                case unchecked((int)0x800A7919):
                    exception = new OutOfMemoryException();

                    if (errorCode != __HResults.E_OUTOFMEMORY)
                        shouldDisplayHR = true;

                    break;
#if ENABLE_WINRT
                case __HResults.E_XAMLPARSEFAILED:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                        message);
                    break;
                case __HResults.E_ELEMENTNOTAVAILABLE:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                        message);
                    break;
                case __HResults.E_ELEMENTNOTENABLED:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", 
                        message);
                    break;
                case __HResults.E_LAYOUTCYCLE:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", 
                        message);
                    break;
#endif // ENABLE_WINRT
                case __HResults.COR_E_AMBIGUOUSMATCH: // AmbiguousMatchException
                case __HResults.COR_E_APPLICATION: // ApplicationException
                case __HResults.COR_E_APPDOMAINUNLOADED: // AppDomainUnloadedException
                case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN: // CannotUnloadAppDomainException
                case __HResults.COR_E_CODECONTRACTFAILED: // ContractException
                case __HResults.COR_E_CONTEXTMARSHAL: // ContextMarshalException
                case __HResults.CORSEC_E_CRYPTO: // CryptographicException
                case __HResults.CORSEC_E_CRYPTO_UNEX_OPER: // CryptographicUnexpectedOperationException
                case __HResults.COR_E_EXECUTIONENGINE: // ExecutionEngineException
                case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException
                case __HResults.COR_E_INVALIDFILTERCRITERIA: // InvalidFilterCriteriaException
                case __HResults.COR_E_INVALIDPROGRAM: // InvalidProgramException
                case __HResults.COR_E_MULTICASTNOTSUPPORTED: // MulticastNotSupportedException
                case __HResults.COR_E_REMOTING: // RemotingException
                case __HResults.COR_E_RUNTIMEWRAPPED: // RuntimeWrappedException
                case __HResults.COR_E_SERVER: // ServerException
                case __HResults.COR_E_STACKOVERFLOW: // StackOverflowException
                case __HResults.CTL_E_OUTOFSTACKSPACE: // StackOverflowException
                case __HResults.COR_E_SYSTEM: // SystemException
                case __HResults.COR_E_TARGET: // TargetException
                case __HResults.COR_E_THREADABORTED: // TargetException
                case __HResults.COR_E_THREADINTERRUPTED: // ThreadInterruptedException
                case __HResults.COR_E_THREADSTATE: // ThreadStateException
                case __HResults.COR_E_THREADSTART: // ThreadStartException
                case __HResults.COR_E_TYPEUNLOADED: // TypeUnloadedException
                case __HResults.CORSEC_E_POLICY_EXCEPTION: // PolicyException
                case __HResults.CORSEC_E_NO_EXEC_PERM: // PolicyException
                case __HResults.CORSEC_E_MIN_GRANT_FAIL: // PolicyException
                case __HResults.CORSEC_E_XMLSYNTAX: // XmlSyntaxException
                case __HResults.ISS_E_ALLOC_TOO_LARGE: // IsolatedStorageException
                case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL: // IsolatedStorageException
                case __HResults.ISS_E_CALLER: // IsolatedStorageException
                case __HResults.ISS_E_CORRUPTED_STORE_FILE: // IsolatedStorageException
                case __HResults.ISS_E_CREATE_DIR: // IsolatedStorageException
                case __HResults.ISS_E_CREATE_MUTEX: // IsolatedStorageException
                case __HResults.ISS_E_DEPRECATE: // IsolatedStorageException
                case __HResults.ISS_E_FILE_NOT_MAPPED: // IsolatedStorageException
                case __HResults.ISS_E_FILE_WRITE: // IsolatedStorageException
                case __HResults.ISS_E_GET_FILE_SIZE: // IsolatedStorageException
                case __HResults.ISS_E_ISOSTORE: // IsolatedStorageException
                case __HResults.ISS_E_LOCK_FAILED: // IsolatedStorageException
                case __HResults.ISS_E_MACHINE: // IsolatedStorageException
                case __HResults.ISS_E_MACHINE_DACL: // IsolatedStorageException
                case __HResults.ISS_E_MAP_VIEW_OF_FILE: // IsolatedStorageException
                case __HResults.ISS_E_OPEN_FILE_MAPPING: // IsolatedStorageException
                case __HResults.ISS_E_OPEN_STORE_FILE: // IsolatedStorageException
                case __HResults.ISS_E_PATH_LENGTH: // IsolatedStorageException
                case __HResults.ISS_E_SET_FILE_POINTER: // IsolatedStorageException
                case __HResults.ISS_E_STORE_NOT_OPEN: // IsolatedStorageException
                case __HResults.ISS_E_STORE_VERSION: // IsolatedStorageException
                case __HResults.ISS_E_TABLE_ROW_NOT_FOUND: // IsolatedStorageException
                case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA: // IsolatedStorageException
                case __HResults.E_FAIL:
                default:
                    break;
            }

            if (exception == null)
            {
                if (createCOMException)
                {
                    exception = new COMException();
                    if (errorCode != __HResults.E_FAIL)
                        shouldDisplayHR = true;
                }
                else
                {
                    exception = new Exception();
                    if (errorCode != __HResults.COR_E_EXCEPTION)
                        shouldDisplayHR = true;
                 }
            }

            bool shouldConstructMessage = false;
            if (hasErrorInfo)
            {
                // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if
                // the message is not available and do not use the shouldDisplayHR setting
                if (message == null)
                    shouldConstructMessage = true;
            }
            else
            {
                // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above
                shouldConstructMessage = shouldDisplayHR;
            }

            if (shouldConstructMessage)
            {
                //
                // Append the HR into error message, just in case the app wants to look at the HR in
                // message to determine behavior.  We didn't expose HResult property until v4.5 and
                // GetHRFromException has side effects so probably Message was their only choice.
                // This behavior is probably not exactly the same as in desktop but it is fine to append
                // more message at the end. In any case, having the HR in the error message are helpful
                // to developers.
                // This makes sure:
                // 1. We always have a HR 0xNNNNNNNN in the message
                // 2. Put in a nice "Exception thrown from HRESULT" message if we can
                // 3. Wrap it in () if there is an existing message
                //

                // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME
                string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString());

                message = ExternalInterop.GetMessage(errorCode);

                // Always make sure we have at least the HRESULT part in retail build or when the message
                // is empty.
                if (message == null)
                    message = hrMessage;
                else
                    message = message + " (" + hrMessage + ")";
            }

            if (message != null)
            {
                // Set message explicitly rather than calling constructor because certain ctors would append a
                // prefix to the message and that is not what we want
                InteropExtensions.SetExceptionMessage(exception, message);
            }

            InteropExtensions.SetExceptionErrorCode(exception, errorCode);

            return exception;
        }
Beispiel #23
0
 private static bool IsRejectedCall(COMException cex)
 {
     // "Call was rejected by callee. (Exception from HRESULT: 0x80010001 (RPC_E_CALL_REJECTED))"
     unchecked
     {
         return cex.ErrorCode == (int)0x80010001;
     }
 }
Beispiel #24
0
        private void HandleCOMException(COMException cex)
        {
            if (IsContextNotAvailable(cex))
            {
                Debug.WriteLine("Context not available.");
                throw new ContextNotAvailableException(cex);
            }
            if (IsRejectedCall(cex))
            {
                Debug.WriteLine("Rejected call.");
                throw new ContextNotAvailableException(cex);
            }

            try { System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(cex.ErrorCode); }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
        const uint NAME_NOT_FOUND = 0x800A03EC;      // When called from the main thread, but Excel is busy.

        static bool IsRetry(COMException e)
        {
            uint errorCode = (uint)e.ErrorCode;
            switch (errorCode)
            {
                case RPC_E_SERVERCALL_RETRYLATER:
                case VBA_E_IGNORE:
                case NAME_NOT_FOUND:
                case RPC_E_CALL_REJECTED:
                    return true;
                default:
                    return false;
            }
        }
 public StorageAccessDeniedException(COMException innerException)
     : base(message, innerException)
 { }
 public StorageInvalidFormatException(COMException innerException)
     : base(message, innerException)
 { }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="innerException">The inner Exception</param>
 public StorageException(COMException innerException) :
     this(innerException.Message, innerException)
 {
 }
 public StorageFileAlreadyExistsException(COMException innerException)
     : base(message, innerException)
 { }
Beispiel #30
0
        public static List <UserDto> FindUserInActiveDirectory(string searchExpression)
        {
            try
            {
                var result = new List <UserDto>();

                // Bind to the users container.
                _searchRoot = new DirectoryEntry(string.Format("LDAP://{0}/{1}", Storage.Domain, Storage.Container),
                                                 Storage.User, Storage.Password);
                var filter = "(&(objectClass=user){0})"; // "";

                var searchExpressions = searchExpression.Split(' ');
                var addedFilters      = "";
                foreach (var expr in searchExpressions)
                {
                    if (!string.IsNullOrEmpty(expr))
                    {
                        addedFilters += "(|(cn=*" + expr + "*)(name=*" + expr + "*)(sAMAccountName=*" + expr + "*))";
                    }
                    else
                    {
                    }
                }

                if (!string.IsNullOrEmpty(addedFilters))
                {
                    filter = string.Format(filter, string.Format("(|{0})", addedFilters));
                }
                else
                {
                    filter = string.Format(filter, "");
                }

                // Create a DirectorySearcher object.
                _mySearcher = new DirectorySearcher(_searchRoot, filter);
                _mySearcher.CacheResults = true;
                // Create a SearchResultCollection object to hold a collection of SearchResults
                // returned by the FindAll method.
                // _mySearcher.Filter =
                _result = _mySearcher.FindAll();
                // Get search results. For more information, see Getting Search Results.
                // ...
                // This sample uses Try...Catch to catch errors.
                // Create an Exception object. For more information, see System.Exception.
                foreach (SearchResult searchResult in _result)
                {
                    var usr = new UserDto()
                    {
                        Person = new PersonDto()
                    };
                    foreach (var property in searchResult.Properties.PropertyNames)
                    {
                        var propertyName = property.ToString();
                        switch (propertyName)
                        {
                        case "cn":
                            usr.Username = searchResult.Properties[propertyName][0].ToString();
                            break;

                        case "objectsid":
                            usr.UserSid = searchResult.Properties[propertyName][0].ToString();
                            break;

                        case "givenname":
                            usr.Person.FirstName = searchResult.Properties[propertyName][0].ToString();
                            break;

                        case "sn":
                            usr.Person.LastName = searchResult.Properties[propertyName][0].ToString();
                            break;
                        }
                    }

                    result.Add(usr);
                }

                return(result);
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                System.Runtime.InteropServices.COMException exception =
                    new System.Runtime.InteropServices.COMException();
                Console.WriteLine(exception);
            }
            catch (InvalidOperationException)
            {
                InvalidOperationException InvOpEx = new InvalidOperationException();
                Console.WriteLine(InvOpEx.Message);
            }
            catch (NotSupportedException)
            {
                NotSupportedException NotSuppEx = new NotSupportedException();
                Console.WriteLine(NotSuppEx.Message);
            }

            return(null);
        }
 public StorageLogonFailureException(COMException innerException)
     : base(message, innerException)
 { }
 public static void GetException(COMException exception)
 {
     switch ((uint)exception.ErrorCode)
       {
     case WIA_ERROR_BUSY:
       throw new DeviceException("Device is busy. Error code :WIA_ERROR_BUSY", exception, (uint)exception.ErrorCode);
     case WIA_ERROR_DEVICE_COMMUNICATION:
       throw new DeviceException("Device communication error. Error code :WIA_ERROR_DEVICE_COMMUNICATION", exception, (uint)exception.ErrorCode);
     case WIA_ERROR_DEVICE_LOCKED:
       throw new DeviceException("Device is locked. Error code :WIA_ERROR_DEVICE_LOCKED", exception, (uint)exception.ErrorCode);
     case WIA_ERROR_EXCEPTION_IN_DRIVER:
       throw new DeviceException("Exception in driver. Error code :WIA_ERROR_EXCEPTION_IN_DRIVER", exception, (uint)exception.ErrorCode);
     case WIA_ERROR_GENERAL_ERROR:
       throw new DeviceException("General error. Error code :WIA_ERROR_GENERAL_ERROR", exception, (uint)exception.ErrorCode);
     case WIA_ERROR_INCORRECT_HARDWARE_SETTING:
       throw new DeviceException("Incorrect hardware error. Error code :WIA_ERROR_INCORRECT_HARDWARE_SETTING", exception, (uint)exception.ErrorCode);
     case WIA_ERROR_INVALID_COMMAND:
       throw new DeviceException("Invalid command. Error code :WIA_ERROR_INVALID_COMMAND", exception, (uint)exception.ErrorCode);
     case WIA_ERROR_INVALID_DRIVER_RESPONSE:
       throw new DeviceException("Invalid driver response. Error code :WIA_ERROR_INVALID_DRIVER_RESPONSE", exception, (uint)exception.ErrorCode);
     case WIA_ERROR_OFFLINE:
       throw new DeviceException("Device is offline. Error code :WIA_ERROR_OFFLINE", exception, WIA_ERROR_OFFLINE, (uint)exception.ErrorCode);
     case WIA_ERROR_UNABLE_TO_FOCUS:
       throw new DeviceException("Unable to focus. Error code :WIA_ERROR_UNABLE_TO_FOCUS", exception, WIA_ERROR_UNABLE_TO_FOCUS, (uint)exception.ErrorCode);
     default:
       throw new DeviceException("Unknown error. Error code:" + (uint)exception.ErrorCode, exception, (uint)exception.ErrorCode);
       }
 }
 public StorageLockViolationException(COMException innerException)
     : base(message, innerException)
 { }
        public void ThrowIfFailed(string message)
        {
            if (Failed)
            {
                if (string.IsNullOrEmpty(message))
                {
                    message = ToString();
                }
#if DEBUG
                else
                {
                    message += " (" + ToString() + ")";
                }
#endif
                // Wow.  Reflection in a throw call.  Later on this may turn out to have been a bad idea.
                // If you're throwing an exception I assume it's OK for me to take some time to give it back.
                // I want to convert the HRESULT to a more appropriate exception type than COMException.
                // Marshal.ThrowExceptionForHR does this for me, but the general call uses GetErrorInfo
                // if it's set, and then ignores the HRESULT that I've provided.  This makes it so this
                // call works the first time but you get burned on the second.  To avoid this, I use
                // the overload that explicitly ignores the IErrorInfo.
                // In addition, the function doesn't allow me to set the Message unless I go through
                // the process of implementing an IErrorInfo and then use that.  There's no stock
                // implementations of IErrorInfo available and I don't think it's worth the maintenance
                // overhead of doing it, nor would it have significant value over this approach.
                Exception e = Marshal.GetExceptionForHR((int)_value, new IntPtr(-1));
                Assert.IsNotNull(e);
                // ArgumentNullException doesn't have the right constructor parameters,
                // (nor does Win32Exception...)
                // but E_POINTER gets mapped to NullReferenceException,
                // so I don't think it will ever matter.
                Assert.IsFalse(e is ArgumentNullException);

                // If we're not getting anything better than a COMException from Marshal,
                // then at least check the facility and attempt to do better ourselves.
                if (e.GetType() == typeof(COMException))
                {
                    switch (Facility)
                    {
                        case Facility.Win32:
                            e = new Win32Exception(Code, message);
                            break;
                        default:
                            e = new COMException(message, (int)_value);
                            break;
                    }
                }
                else
                {
                    ConstructorInfo cons = e.GetType().GetConstructor(new[] { typeof(string) });
                    if (null != cons)
                    {
                        e = cons.Invoke(new object[] { message }) as Exception;
                        Assert.IsNotNull(e);
                    }
                }
                throw e;
            }
        }
 public StorageNotCurrentException(COMException innerException)
     : base(message, innerException)
 { }
Beispiel #36
0
 private static bool IsContextNotAvailable(COMException cex)
 {
     unchecked
     {
         return cex.ErrorCode == (int)0x89711006;
     }
 }
 public StorageInvalidOperationException(COMException innerException)
     : base(message, innerException)
 {
     // Debug.Fail("Invalid Operation using Storage: " + innerException.Message);
 }
 public StoragePathNotFoundException(COMException innerException)
     : base(message, innerException)
 { }
Beispiel #39
0
        /// <summary>
        /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException.
        /// and in winrt and marshal APIs as Exception.
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        /// <param name="createCOMException"></param>
        /// <returns></returns>
        internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo)
        {
            if (errorCode >= 0)
            {
                return(null);
            }

            Exception exception = null;

            bool shouldDisplayHR = false;

            switch (errorCode)
            {
            case __HResults.COR_E_NOTFINITENUMBER:     // NotFiniteNumberException
            case __HResults.COR_E_ARITHMETIC:
                exception = new ArithmeticException();
                break;

            case __HResults.COR_E_ARGUMENT:
            case unchecked ((int)0x800A01C1):
            case unchecked ((int)0x800A01C2):
            case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT:
                exception = new ArgumentException();

                if (errorCode != __HResults.COR_E_ARGUMENT)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.E_BOUNDS:
            case __HResults.COR_E_ARGUMENTOUTOFRANGE:
            case __HResults.ERROR_NO_UNICODE_TRANSLATION:
                exception = new ArgumentOutOfRangeException();

                if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_ARRAYTYPEMISMATCH:
                exception = new ArrayTypeMismatchException();
                break;

            case __HResults.COR_E_BADIMAGEFORMAT:
            case __HResults.CLDB_E_FILE_OLDVER:
            case __HResults.CLDB_E_INDEX_NOTFOUND:
            case __HResults.CLDB_E_FILE_CORRUPT:
            case __HResults.COR_E_NEWER_RUNTIME:
            case __HResults.COR_E_ASSEMBLYEXPECTED:
            case __HResults.ERROR_BAD_EXE_FORMAT:
            case __HResults.ERROR_EXE_MARKED_INVALID:
            case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT:
            case __HResults.ERROR_NOACCESS:
            case __HResults.ERROR_INVALID_ORDINAL:
            case __HResults.ERROR_INVALID_DLL:
            case __HResults.ERROR_FILE_CORRUPT:
            case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY:
            case __HResults.META_E_BAD_SIGNATURE:
                exception = new BadImageFormatException();

                // Always show HR for BadImageFormatException
                shouldDisplayHR = true;

                break;

            case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT:
                exception = new FormatException();
                break;     // CustomAttributeFormatException

            case __HResults.COR_E_DATAMISALIGNED:
                exception = InteropExtensions.CreateDataMisalignedException(message);     // TODO: Do we need to add msg here?
                break;

            case __HResults.COR_E_DIVIDEBYZERO:
            case __HResults.CTL_E_DIVISIONBYZERO:
                exception = new DivideByZeroException();

                if (errorCode != __HResults.COR_E_DIVIDEBYZERO)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_DLLNOTFOUND:
#if ENABLE_WINRT
                exception = new DllNotFoundException();
#endif
                break;

            case __HResults.COR_E_DUPLICATEWAITOBJECT:
                exception = new ArgumentException();
                break;     // DuplicateWaitObjectException

            case __HResults.COR_E_ENDOFSTREAM:
            case unchecked ((int)0x800A003E):
                exception = new CoreFX_IO::System.IO.EndOfStreamException();

                if (errorCode != __HResults.COR_E_ENDOFSTREAM)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_TYPEACCESS:     // TypeAccessException
            case __HResults.COR_E_ENTRYPOINTNOTFOUND:
                exception = new TypeLoadException();

                break;     // EntryPointNotFoundException

            case __HResults.COR_E_EXCEPTION:
                exception = new Exception();
                break;

            case __HResults.COR_E_DIRECTORYNOTFOUND:
            case __HResults.STG_E_PATHNOTFOUND:
            case __HResults.CTL_E_PATHNOTFOUND:
                exception = new System.IO.DirectoryNotFoundException();

                if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_FILELOAD:
            case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION:
            case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED:
            case __HResults.FUSION_E_LOADFROM_BLOCKED:
            case __HResults.FUSION_E_CACHEFILE_FAILED:
            case __HResults.FUSION_E_ASM_MODULE_MISSING:
            case __HResults.FUSION_E_INVALID_NAME:
            case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED:
            case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH:
            case __HResults.COR_E_MODULE_HASH_CHECK_FAILED:
            case __HResults.FUSION_E_REF_DEF_MISMATCH:
            case __HResults.SECURITY_E_INCOMPATIBLE_SHARE:
            case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE:
            case __HResults.SECURITY_E_UNVERIFIABLE:
            case __HResults.COR_E_FIXUPSINEXE:
            case __HResults.ERROR_TOO_MANY_OPEN_FILES:
            case __HResults.ERROR_SHARING_VIOLATION:
            case __HResults.ERROR_LOCK_VIOLATION:
            case __HResults.ERROR_OPEN_FAILED:
            case __HResults.ERROR_DISK_CORRUPT:
            case __HResults.ERROR_UNRECOGNIZED_VOLUME:
            case __HResults.ERROR_DLL_INIT_FAILED:
            case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED:
            case __HResults.CORSEC_E_MISSING_STRONGNAME:
            case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS:
            case __HResults.ERROR_FILE_INVALID:
                exception = new System.IO.FileLoadException();

                shouldDisplayHR = true;
                break;

            case __HResults.COR_E_PATHTOOLONG:
                exception = new System.IO.PathTooLongException();
                break;

            case __HResults.COR_E_IO:
            case __HResults.CTL_E_DEVICEIOERROR:
            case unchecked ((int)0x800A793C):
            case unchecked ((int)0x800A793D):
                exception = new System.IO.IOException();

                if (errorCode != __HResults.COR_E_IO)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.ERROR_FILE_NOT_FOUND:
            case __HResults.ERROR_MOD_NOT_FOUND:
            case __HResults.ERROR_INVALID_NAME:
            case __HResults.CTL_E_FILENOTFOUND:
            case __HResults.ERROR_BAD_NET_NAME:
            case __HResults.ERROR_BAD_NETPATH:
            case __HResults.ERROR_NOT_READY:
            case __HResults.ERROR_WRONG_TARGET_NAME:
            case __HResults.INET_E_UNKNOWN_PROTOCOL:
            case __HResults.INET_E_CONNECTION_TIMEOUT:
            case __HResults.INET_E_CANNOT_CONNECT:
            case __HResults.INET_E_RESOURCE_NOT_FOUND:
            case __HResults.INET_E_OBJECT_NOT_FOUND:
            case __HResults.INET_E_DOWNLOAD_FAILURE:
            case __HResults.INET_E_DATA_NOT_AVAILABLE:
            case __HResults.ERROR_DLL_NOT_FOUND:
            case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW:
            case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH:
            case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND:
                exception = new System.IO.FileNotFoundException();

                shouldDisplayHR = true;
                break;

            case __HResults.COR_E_FORMAT:
                exception = new FormatException();
                break;

            case __HResults.COR_E_INDEXOUTOFRANGE:
            case unchecked ((int)0x800a0009):
                exception = new IndexOutOfRangeException();

                if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_INVALIDCAST:
                exception = new InvalidCastException();
                break;

            case __HResults.COR_E_INVALIDCOMOBJECT:
                exception = new InvalidComObjectException();
                break;

            case __HResults.COR_E_INVALIDOLEVARIANTTYPE:
                exception = new InvalidOleVariantTypeException();
                break;

            case __HResults.COR_E_INVALIDOPERATION:
            case __HResults.E_ILLEGAL_STATE_CHANGE:
            case __HResults.E_ILLEGAL_METHOD_CALL:
            case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT:
            case __HResults.APPMODEL_ERROR_NO_PACKAGE:
                exception = new InvalidOperationException();

                if (errorCode != __HResults.COR_E_INVALIDOPERATION)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_MARSHALDIRECTIVE:
                exception = new MarshalDirectiveException();
                break;

            case __HResults.COR_E_METHODACCESS:            // MethodAccessException
            case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException
            case __HResults.COR_E_FIELDACCESS:
            case __HResults.COR_E_MEMBERACCESS:
                exception = new MemberAccessException();

                if (errorCode != __HResults.COR_E_METHODACCESS)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_MISSINGFIELD:     // MissingFieldException
            case __HResults.COR_E_MISSINGMETHOD:    // MissingMethodException
            case __HResults.COR_E_MISSINGMEMBER:
            case unchecked ((int)0x800A01CD):
                exception = new MissingMemberException();
                break;

            case __HResults.COR_E_MISSINGMANIFESTRESOURCE:
                exception = new System.Resources.MissingManifestResourceException();
                break;

            case __HResults.COR_E_NOTSUPPORTED:
            case unchecked ((int)0x800A01B6):
            case unchecked ((int)0x800A01BD):
            case unchecked ((int)0x800A01CA):
            case unchecked ((int)0x800A01CB):
                exception = new NotSupportedException();

                if (errorCode != __HResults.COR_E_NOTSUPPORTED)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_NULLREFERENCE:
                exception = new NullReferenceException();
                break;

            case __HResults.COR_E_OBJECTDISPOSED:
            case __HResults.RO_E_CLOSED:
                // No default constructor
                exception = new ObjectDisposedException(String.Empty);
                break;

            case __HResults.COR_E_OPERATIONCANCELED:
#if ENABLE_WINRT
                exception = new OperationCanceledException();
#endif
                break;

            case __HResults.COR_E_OVERFLOW:
            case __HResults.CTL_E_OVERFLOW:
                exception = new OverflowException();
                break;

            case __HResults.COR_E_PLATFORMNOTSUPPORTED:
                exception = new PlatformNotSupportedException(message);
                break;

            case __HResults.COR_E_RANK:
                exception = new RankException();
                break;

            case __HResults.COR_E_REFLECTIONTYPELOAD:
#if ENABLE_WINRT
                exception = new System.Reflection.ReflectionTypeLoadException(null, null);
#endif
                break;

            case __HResults.COR_E_SECURITY:
            case __HResults.CORSEC_E_INVALID_STRONGNAME:
            case __HResults.CTL_E_PERMISSIONDENIED:
            case unchecked ((int)0x800A01A3):
            case __HResults.CORSEC_E_INVALID_PUBLICKEY:
            case __HResults.CORSEC_E_SIGNATURE_MISMATCH:
                exception = new System.Security.SecurityException();
                break;

            case __HResults.COR_E_SAFEARRAYRANKMISMATCH:
                exception = new SafeArrayRankMismatchException();
                break;

            case __HResults.COR_E_SAFEARRAYTYPEMISMATCH:
                exception = new SafeArrayTypeMismatchException();
                break;

            case __HResults.COR_E_SERIALIZATION:
                exception = new System.Runtime.Serialization.SerializationException(message);
                break;

            case __HResults.COR_E_SYNCHRONIZATIONLOCK:
                exception = new System.Threading.SynchronizationLockException();
                break;

            case __HResults.COR_E_TARGETINVOCATION:
                exception = new System.Reflection.TargetInvocationException(null);
                break;

            case __HResults.COR_E_TARGETPARAMCOUNT:
                exception = new System.Reflection.TargetParameterCountException();
                break;

            case __HResults.COR_E_TYPEINITIALIZATION:
                exception = InteropExtensions.CreateTypeInitializationException(message);
                break;

            case __HResults.COR_E_TYPELOAD:
            case __HResults.RO_E_METADATA_NAME_NOT_FOUND:
            case __HResults.CLR_E_BIND_TYPE_NOT_FOUND:
                exception = new TypeLoadException();

                if (errorCode != __HResults.COR_E_TYPELOAD)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_UNAUTHORIZEDACCESS:
            case __HResults.CTL_E_PATHFILEACCESSERROR:
            case unchecked ((int)0x800A014F):
                exception = new UnauthorizedAccessException();

                shouldDisplayHR = true;

                break;

            case __HResults.COR_E_VERIFICATION:
                exception = new System.Security.VerificationException();
                break;

            case __HResults.E_NOTIMPL:
                exception = new NotImplementedException();
                break;

            case __HResults.E_OUTOFMEMORY:
            case __HResults.CTL_E_OUTOFMEMORY:
            case unchecked ((int)0x800A7919):
                exception = new OutOfMemoryException();

                if (errorCode != __HResults.E_OUTOFMEMORY)
                {
                    shouldDisplayHR = true;
                }

                break;

#if ENABLE_WINRT
            case __HResults.E_XAMLPARSEFAILED:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_ELEMENTNOTAVAILABLE:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_ELEMENTNOTENABLED:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_LAYOUTCYCLE:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;
#endif // ENABLE_WINRT
            case __HResults.COR_E_AMBIGUOUSMATCH:     // AmbiguousMatchException
            case __HResults.COR_E_APPLICATION:     // ApplicationException
            case __HResults.COR_E_APPDOMAINUNLOADED:          // AppDomainUnloadedException
            case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN:      // CannotUnloadAppDomainException
            case __HResults.COR_E_CODECONTRACTFAILED:         // ContractException
            case __HResults.COR_E_CONTEXTMARSHAL:             // ContextMarshalException
            case __HResults.CORSEC_E_CRYPTO:                  // CryptographicException
            case __HResults.CORSEC_E_CRYPTO_UNEX_OPER:        // CryptographicUnexpectedOperationException
            case __HResults.COR_E_EXECUTIONENGINE:            // ExecutionEngineException
            case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException
            case __HResults.COR_E_INVALIDFILTERCRITERIA:      // InvalidFilterCriteriaException
            case __HResults.COR_E_INVALIDPROGRAM:             // InvalidProgramException
            case __HResults.COR_E_MULTICASTNOTSUPPORTED:      // MulticastNotSupportedException
            case __HResults.COR_E_REMOTING:                   // RemotingException
            case __HResults.COR_E_RUNTIMEWRAPPED:             // RuntimeWrappedException
            case __HResults.COR_E_SERVER:                     // ServerException
            case __HResults.COR_E_STACKOVERFLOW:              // StackOverflowException
            case __HResults.CTL_E_OUTOFSTACKSPACE:            // StackOverflowException
            case __HResults.COR_E_SYSTEM:                     // SystemException
            case __HResults.COR_E_TARGET:                     // TargetException
            case __HResults.COR_E_THREADABORTED:              // TargetException
            case __HResults.COR_E_THREADINTERRUPTED:          // ThreadInterruptedException
            case __HResults.COR_E_THREADSTATE:                // ThreadStateException
            case __HResults.COR_E_THREADSTART:                // ThreadStartException
            case __HResults.COR_E_TYPEUNLOADED:               // TypeUnloadedException
            case __HResults.CORSEC_E_POLICY_EXCEPTION:        // PolicyException
            case __HResults.CORSEC_E_NO_EXEC_PERM:            // PolicyException
            case __HResults.CORSEC_E_MIN_GRANT_FAIL:          // PolicyException
            case __HResults.CORSEC_E_XMLSYNTAX:               // XmlSyntaxException
            case __HResults.ISS_E_ALLOC_TOO_LARGE:            // IsolatedStorageException
            case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL:       // IsolatedStorageException
            case __HResults.ISS_E_CALLER:                     // IsolatedStorageException
            case __HResults.ISS_E_CORRUPTED_STORE_FILE:       // IsolatedStorageException
            case __HResults.ISS_E_CREATE_DIR:                 // IsolatedStorageException
            case __HResults.ISS_E_CREATE_MUTEX:               // IsolatedStorageException
            case __HResults.ISS_E_DEPRECATE:                  // IsolatedStorageException
            case __HResults.ISS_E_FILE_NOT_MAPPED:            // IsolatedStorageException
            case __HResults.ISS_E_FILE_WRITE:                 // IsolatedStorageException
            case __HResults.ISS_E_GET_FILE_SIZE:              // IsolatedStorageException
            case __HResults.ISS_E_ISOSTORE:                   // IsolatedStorageException
            case __HResults.ISS_E_LOCK_FAILED:                // IsolatedStorageException
            case __HResults.ISS_E_MACHINE:                    // IsolatedStorageException
            case __HResults.ISS_E_MACHINE_DACL:               // IsolatedStorageException
            case __HResults.ISS_E_MAP_VIEW_OF_FILE:           // IsolatedStorageException
            case __HResults.ISS_E_OPEN_FILE_MAPPING:          // IsolatedStorageException
            case __HResults.ISS_E_OPEN_STORE_FILE:            // IsolatedStorageException
            case __HResults.ISS_E_PATH_LENGTH:                // IsolatedStorageException
            case __HResults.ISS_E_SET_FILE_POINTER:           // IsolatedStorageException
            case __HResults.ISS_E_STORE_NOT_OPEN:             // IsolatedStorageException
            case __HResults.ISS_E_STORE_VERSION:              // IsolatedStorageException
            case __HResults.ISS_E_TABLE_ROW_NOT_FOUND:        // IsolatedStorageException
            case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA:    // IsolatedStorageException
            case __HResults.E_FAIL:
            default:
                break;
            }

            if (exception == null)
            {
                if (createCOMException)
                {
                    exception = new COMException();
                    if (errorCode != __HResults.E_FAIL)
                    {
                        shouldDisplayHR = true;
                    }
                }
                else
                {
                    exception = new Exception();
                    if (errorCode != __HResults.COR_E_EXCEPTION)
                    {
                        shouldDisplayHR = true;
                    }
                }
            }

            bool shouldConstructMessage = false;
            if (hasErrorInfo)
            {
                // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if
                // the message is not available and do not use the shouldDisplayHR setting
                if (message == null)
                {
                    shouldConstructMessage = true;
                }
            }
            else
            {
                // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above
                shouldConstructMessage = shouldDisplayHR;
            }

            if (shouldConstructMessage)
            {
                //
                // Append the HR into error message, just in case the app wants to look at the HR in
                // message to determine behavior.  We didn't expose HResult property until v4.5 and
                // GetHRFromException has side effects so probably Message was their only choice.
                // This behavior is probably not exactly the same as in desktop but it is fine to append
                // more message at the end. In any case, having the HR in the error message are helpful
                // to developers.
                // This makes sure:
                // 1. We always have a HR 0xNNNNNNNN in the message
                // 2. Put in a nice "Exception thrown from HRESULT" message if we can
                // 3. Wrap it in () if there is an existing message
                //

                // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME
                string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString());

                message = ExternalInterop.GetMessage(errorCode);

                // Always make sure we have at least the HRESULT part in retail build or when the message
                // is empty.
                if (message == null)
                {
                    message = hrMessage;
                }
                else
                {
                    message = message + " (" + hrMessage + ")";
                }
            }

            if (message != null)
            {
                // Set message explicitly rather than calling constructor because certain ctors would append a
                // prefix to the message and that is not what we want
                InteropExtensions.SetExceptionMessage(exception, message);
            }

            InteropExtensions.SetExceptionErrorCode(exception, errorCode);

            return(exception);
        }