public void CanBeCreatedWithMessageAndExceptionTest() { var exceptionMessage = Guid.NewGuid().ToString(); var innerExceptionMessage = Guid.NewGuid().ToString(); var innerException = new TypeLoadException(innerExceptionMessage); var target = new InvalidHtmlElementMatchException(exceptionMessage, innerException); target.Message.Should().Be(exceptionMessage); target.InnerException.Should().Be(innerException); }
public void CanBeCreatedWithMessageAndExceptionTest() { var exceptionMessage = Guid.NewGuid().ToString(); var innerExceptionMessage = Guid.NewGuid().ToString(); var innerException = new TypeLoadException(innerExceptionMessage); var target = new HttpOutcomeException(exceptionMessage, innerException); target.Message.Should().Be(exceptionMessage); target.InnerException.Should().Be(innerException); }
public void CanBeSerializedAndDeserializedTest() { var exceptionMessage = Guid.NewGuid().ToString(); var innerExceptionMessage = Guid.NewGuid().ToString(); var innerException = new TypeLoadException(innerExceptionMessage); var target = new InvalidHtmlElementMatchException(exceptionMessage, innerException); using (var ms = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(ms, target); ms.Seek(0, SeekOrigin.Begin); var outputException = formatter.Deserialize(ms) as InvalidHtmlElementMatchException; outputException.Should().NotBeNull(); target.Message.Should().Be(exceptionMessage); target.InnerException.Should().Be(innerException); } }
private void SetMessageField() { if (this._message == null) { if (this.ClassName == null && this.ResourceId == 0) { this._message = Environment.GetResourceString("Arg_TypeLoadException"); return; } if (this.AssemblyName == null) { this.AssemblyName = Environment.GetResourceString("IO_UnknownFileName"); } if (this.ClassName == null) { this.ClassName = Environment.GetResourceString("IO_UnknownFileName"); } string format = null; TypeLoadException.GetTypeLoadExceptionMessage(this.ResourceId, JitHelpers.GetStringHandleOnStack(ref format)); this._message = string.Format(CultureInfo.CurrentCulture, format, this.ClassName, this.AssemblyName, this.MessageArg); } }
public object GetValue(ITypeResolutionService typeResolver) { if (this.value != null) { return this.value; } object obj2 = null; if (this.FileRefFullPath != null) { if (this.ResolveType(this.FileRefType, typeResolver) != null) { if (this.FileRefTextEncoding != null) { this.fileRef = new ResXFileRef(this.FileRefFullPath, this.FileRefType, Encoding.GetEncoding(this.FileRefTextEncoding)); } else { this.fileRef = new ResXFileRef(this.FileRefFullPath, this.FileRefType); } return TypeDescriptor.GetConverter(typeof(ResXFileRef)).ConvertFrom(this.fileRef.ToString()); } TypeLoadException exception = new TypeLoadException(System.Windows.Forms.SR.GetString("TypeLoadExceptionShort", new object[] { this.FileRefType })); throw exception; } if ((obj2 == null) && (this.nodeInfo.ValueData != null)) { return this.GenerateObjectFromDataNodeInfo(this.nodeInfo, typeResolver); } return null; }
private object GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeResolutionService typeResolver) { object obj2 = null; string mimeType = dataNodeInfo.MimeType; string typeName = ((dataNodeInfo.TypeName == null) || (dataNodeInfo.TypeName.Length == 0)) ? MultitargetUtil.GetAssemblyQualifiedName(typeof(string), this.typeNameConverter) : dataNodeInfo.TypeName; if ((mimeType != null) && (mimeType.Length > 0)) { if ((string.Equals(mimeType, ResXResourceWriter.BinSerializedObjectMimeType) || string.Equals(mimeType, ResXResourceWriter.Beta2CompatSerializedObjectMimeType)) || string.Equals(mimeType, ResXResourceWriter.CompatBinSerializedObjectMimeType)) { byte[] buffer = FromBase64WrappedString(dataNodeInfo.ValueData); if (this.binaryFormatter == null) { this.binaryFormatter = new BinaryFormatter(); this.binaryFormatter.Binder = new ResXSerializationBinder(typeResolver); } IFormatter binaryFormatter = this.binaryFormatter; if ((buffer != null) && (buffer.Length > 0)) { obj2 = binaryFormatter.Deserialize(new MemoryStream(buffer)); if (obj2 is ResXNullRef) { obj2 = null; } } return obj2; } if (string.Equals(mimeType, ResXResourceWriter.SoapSerializedObjectMimeType) || string.Equals(mimeType, ResXResourceWriter.CompatSoapSerializedObjectMimeType)) { byte[] buffer2 = FromBase64WrappedString(dataNodeInfo.ValueData); if ((buffer2 != null) && (buffer2.Length > 0)) { obj2 = this.CreateSoapFormatter().Deserialize(new MemoryStream(buffer2)); if (obj2 is ResXNullRef) { obj2 = null; } } return obj2; } if ((!string.Equals(mimeType, ResXResourceWriter.ByteArraySerializedObjectMimeType) || (typeName == null)) || (typeName.Length <= 0)) { return obj2; } System.Type type = this.ResolveType(typeName, typeResolver); if (type != null) { TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertFrom(typeof(byte[]))) { byte[] buffer3 = FromBase64WrappedString(dataNodeInfo.ValueData); if (buffer3 != null) { obj2 = converter.ConvertFrom(buffer3); } } return obj2; } string str6 = System.Windows.Forms.SR.GetString("TypeLoadException", new object[] { typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X }); XmlException exception = new XmlException(str6, null, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); TypeLoadException exception2 = new TypeLoadException(str6, exception); throw exception2; } if ((typeName == null) || (typeName.Length <= 0)) { return obj2; } System.Type type2 = this.ResolveType(typeName, typeResolver); if (type2 != null) { if (type2 == typeof(ResXNullRef)) { return null; } if ((typeName.IndexOf("System.Byte[]") != -1) && (typeName.IndexOf("mscorlib") != -1)) { return FromBase64WrappedString(dataNodeInfo.ValueData); } TypeConverter converter2 = TypeDescriptor.GetConverter(type2); if (!converter2.CanConvertFrom(typeof(string))) { return obj2; } string valueData = dataNodeInfo.ValueData; try { return converter2.ConvertFromInvariantString(valueData); } catch (NotSupportedException exception3) { string str8 = System.Windows.Forms.SR.GetString("NotSupported", new object[] { typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X, exception3.Message }); XmlException innerException = new XmlException(str8, exception3, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); NotSupportedException exception5 = new NotSupportedException(str8, innerException); throw exception5; } } string message = System.Windows.Forms.SR.GetString("TypeLoadException", new object[] { typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X }); XmlException inner = new XmlException(message, null, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); TypeLoadException exception7 = new TypeLoadException(message, inner); throw exception7; }
/// <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; }
/// <include file='doc\ResXDataNode.uex' path='docs/doc[@for="ResXDataNode.GetValue"]/*' /> /// <devdoc> /// Get the value contained in this datanode /// </devdoc> public object GetValue(ITypeResolutionService typeResolver) { if(value != null) { return value; } object result = null; if(FileRefFullPath != null) { Type objectType = ResolveType(FileRefType , typeResolver); if(objectType != null) { // we have the FQN for this type if(FileRefTextEncoding != null) { fileRef = new ResXFileRef(FileRefFullPath, FileRefType, Encoding.GetEncoding(FileRefTextEncoding)); } else { fileRef = new ResXFileRef(FileRefFullPath, FileRefType); } TypeConverter tc = TypeDescriptor.GetConverter(typeof(ResXFileRef)); result = tc.ConvertFrom(fileRef.ToString()); } else { string newMessage = SR.GetString(SR.TypeLoadExceptionShort, FileRefType); TypeLoadException newTle = new TypeLoadException(newMessage); throw (newTle); } } else if(result == null && nodeInfo.ValueData!= null) { // it's embedded, we deserialize it result = GenerateObjectFromDataNodeInfo(nodeInfo, typeResolver); } else { // schema is wrong and say minOccur for Value is 0, // but it's too late to change it... // we need to return null here vswhidbey 180605 return null; } return result; }
private object GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeResolutionService typeResolver) { object result = null; string mimeTypeName = dataNodeInfo.MimeType; // default behavior: if we dont have a type name, it's a string string typeName = (dataNodeInfo.TypeName == null || dataNodeInfo.TypeName.Length==0 ? MultitargetUtil.GetAssemblyQualifiedName(typeof(string), this.typeNameConverter) : dataNodeInfo.TypeName); if (mimeTypeName != null && mimeTypeName.Length > 0) { if (String.Equals(mimeTypeName, ResXResourceWriter.BinSerializedObjectMimeType) || String.Equals(mimeTypeName, ResXResourceWriter.Beta2CompatSerializedObjectMimeType) || String.Equals(mimeTypeName, ResXResourceWriter.CompatBinSerializedObjectMimeType)) { string text = dataNodeInfo.ValueData; byte[] serializedData; serializedData = FromBase64WrappedString(text); if (binaryFormatter == null) { binaryFormatter = new BinaryFormatter(); binaryFormatter.Binder = new ResXSerializationBinder(typeResolver); } IFormatter formatter = binaryFormatter; if (serializedData != null && serializedData.Length > 0) { result = formatter.Deserialize(new MemoryStream(serializedData)); if (result is ResXNullRef) { result = null; } } } #if !SYSTEM_WEB // System.Web does not link with the Soap assembly else if (String.Equals(mimeTypeName, ResXResourceWriter.SoapSerializedObjectMimeType) || String.Equals(mimeTypeName, ResXResourceWriter.CompatSoapSerializedObjectMimeType)) { string text = dataNodeInfo.ValueData; byte[] serializedData; serializedData = FromBase64WrappedString(text); if (serializedData != null && serializedData.Length > 0) { // Performance : don't inline a new SoapFormatter here. That will always bring in // the soap assembly, which we don't want. Throw this in another // function so the class doesn't have to get loaded. // IFormatter formatter = CreateSoapFormatter(); result = formatter.Deserialize(new MemoryStream(serializedData)); if (result is ResXNullRef) { result = null; } } } #endif else if (String.Equals(mimeTypeName, ResXResourceWriter.ByteArraySerializedObjectMimeType)) { if (typeName != null && typeName.Length > 0) { Type type = ResolveType(typeName, typeResolver); if (type != null) { TypeConverter tc = TypeDescriptor.GetConverter(type); if (tc.CanConvertFrom(typeof(byte[]))) { string text = dataNodeInfo.ValueData; byte[] serializedData; serializedData = FromBase64WrappedString(text); if (serializedData != null) { result = tc.ConvertFrom(serializedData); } } } else { string newMessage = SR.GetString(SR.TypeLoadException, typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); XmlException xml = new XmlException(newMessage, null, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); TypeLoadException newTle = new TypeLoadException(newMessage, xml); throw newTle; } } } } else if (typeName != null && typeName.Length > 0) { Type type = ResolveType(typeName, typeResolver); if (type != null) { if (type == typeof(ResXNullRef)) { result = null; } else if (typeName.IndexOf("System.Byte[]") != -1 && typeName.IndexOf("mscorlib") != -1) { // Handle byte[]'s, which are stored as base-64 encoded strings. // We can't hard-code byte[] type name due to version number // updates & potential whitespace issues with ResX files. result = FromBase64WrappedString(dataNodeInfo.ValueData); } else { TypeConverter tc = TypeDescriptor.GetConverter(type); if (tc.CanConvertFrom(typeof(string))) { string text = dataNodeInfo.ValueData; try { result = tc.ConvertFromInvariantString(text); } catch (NotSupportedException nse) { string newMessage = SR.GetString(SR.NotSupported, typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X, nse.Message); XmlException xml = new XmlException(newMessage, nse, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); NotSupportedException newNse = new NotSupportedException(newMessage, xml); throw newNse; } } else { Debug.WriteLine("Converter for " + type.FullName + " doesn't support string conversion"); } } } else { string newMessage = SR.GetString(SR.TypeLoadException, typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); XmlException xml = new XmlException(newMessage, null, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); TypeLoadException newTle = new TypeLoadException(newMessage, xml); throw newTle; } } else { // if mimeTypeName and typeName are not filled in, the value must be a string Debug.Assert(value is string, "Resource entries with no Type or MimeType must be encoded as strings"); } return result; }
internal static TypeLoadException TypeLoad(string error) { TypeLoadException e = new TypeLoadException(error); TraceExceptionAsReturnValue(e); return e; }
/// <summary> /// Uses a file path to load an assembly. Then instantiates the requested type by searching interfaces. /// Returns an object instantiated by the Activator, using fully-qualified combined assembly-type supplied. /// Assembly parameter example: "Microsoft.ApplicationBlocks.ApplicationUpdater,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null" /// Type parameter example: "Microsoft.ApplicationBlocks.ApplicationUpdater.Validators.RSAValidator" /// </summary> /// <param name="filePath">full path to assembly</param> /// <param name="interfaceToActivate">the Type representing the interface to activate</param> /// <returns></returns> public static object Create( string filePath, Type interfaceToActivate ) { Assembly asm = null; Type typeInstance = null; Type[] types = null; Object obj = null; try { asm = Assembly.LoadFrom( filePath ); types = asm.GetTypes(); // walk through all types in assembly, find the one that IS IPP and use its info foreach( Type type in types ) { // search for interface by string name in this type typeInstance = type.GetInterface( interfaceToActivate.FullName, false ); // if we find the interface, return the type that implements it if( null != typeInstance ) { // we found the first instance of the given interface // THERE MAY BE MORE but this is a convenience method. typeInstance = type; break; } } obj = asm.CreateInstance( typeInstance.FullName ); } catch( Exception e ) { string error = ApplicationUpdateManager.TraceWrite( "[GenericFactory.Create]", "RES_EXCEPTION_CantCreateInstanceFromFilePath", filePath, interfaceToActivate ); TypeLoadException tle = new TypeLoadException( error, e ); ExceptionManager.Publish ( tle ); throw tle; } return obj; }
/// <summary> /// Returns an object instantiated by the Activator, using fully-qualified asm/type supplied. /// Permits construction arguments to be supplied which it passes to the object's constructor on instantiation. /// </summary> /// <param name="assemblyName">fully-qualified assembly name</param> /// <param name="typeName">the type name</param> /// <param name="constructorArguments">constructor arguments for type to be created</param> /// <returns>instance of requested assembly/type typed as System.Object</returns> public static object Create( string assemblyName, string typeName, object[] constructorArguments ) { Assembly assemblyInstance = null; Type typeInstance = null; try { // use full asm name to get assembly instance assemblyInstance = Assembly.Load( assemblyName.Trim() ); } catch ( Exception e ) { string error = ApplicationUpdateManager.TraceWrite( "[GenericFactory.Create]", "RES_EXCEPTION_CantLoadAssembly", assemblyName, typeName ); TypeLoadException tle = new TypeLoadException( error, e ); ExceptionManager.Publish ( tle ); throw tle; } try { // use type name to get type from asm; note we WANT case specificity typeInstance = assemblyInstance.GetType( typeName.Trim(), true, false ); // now attempt to actually create an instance, passing constructor args if available if( constructorArguments != null ) { return Activator.CreateInstance( typeInstance, constructorArguments ); } else { return Activator.CreateInstance( typeInstance ); } } catch( Exception e ) { string error = ApplicationUpdateManager.TraceWrite( "[GenericFactory.Create]", "RES_EXCEPTION_CantCreateInstanceUsingActivate", assemblyName, typeName ); TypeLoadException tle = new TypeLoadException( error, e ); ExceptionManager.Publish ( tle ); throw tle; } }