public void ReturnsCastObject() { var expected = new InvalidCastException(); var actual = Assert.IsAssignableFrom<InvalidCastException>(expected); Assert.Same(expected, actual); }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize the InvalidCastException instance"); try { InvalidCastException myException = new InvalidCastException(); if (myException == null) { TestLibrary.TestFramework.LogError("001", "the InvalidCastException instance creating failed"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize the InvalidCastException instance with message 2"); try { string message = null; InvalidCastException myException = new InvalidCastException(message); if (myException == null || myException.Message == null) { TestLibrary.TestFramework.LogError("003", "Initialize the InvalidCastException instance with null message not create"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize the InvalidCastException instance with message 1"); try { string message = "HelloWorld"; InvalidCastException myException = new InvalidCastException(message); if (myException == null || myException.Message != message) { TestLibrary.TestFramework.LogError("001", "the InvalidCastException with message instance creating failed"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3:Initialize the InvalidCastException instance with message and InnerException 3"); try { string message = null; InvalidCastException myException = new InvalidCastException(message, null); if (myException == null || myException.Message == null || myException.InnerException != null) { TestLibrary.TestFramework.LogError("005", "Initialize the InvalidCastException instance with null message and null InnerException not succeed"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize the InvalidCastException instance with message and InnerException 2"); try { string message = null; ArgumentException innerException = new ArgumentException(); InvalidCastException myException = new InvalidCastException(message, innerException); if (myException == null || myException.Message == null || !myException.InnerException.Equals(innerException)) { TestLibrary.TestFramework.LogError("003", "Initialize the InvalidCastException instance with null message not succeed"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; }
// returns false with both outs null for no such feature internal static bool TryParseFeature(string featureString, PluginLoader.PluginMetadata plugin, out Feature feature, out Exception failException, out bool featureValid, out FeatureParse parsed, FeatureParse?preParsed = null) { failException = null; feature = null; featureValid = false; if (preParsed == null) { var builder = new StringBuilder(); string name = null; var parameters = new List <string>(); bool escape = false; int parens = 0; bool removeWhitespace = true; foreach (var chr in featureString) { if (escape) { builder.Append(chr); escape = false; } else { switch (chr) { case '\\': escape = true; break; case '(': parens++; if (parens != 1) { goto default; } removeWhitespace = true; name = builder.ToString(); builder.Clear(); break; case ')': parens--; if (parens != 0) { goto default; } goto case ','; case ',': if (parens > 1) { goto default; } parameters.Add(builder.ToString()); builder.Clear(); removeWhitespace = true; break; default: if (removeWhitespace && !char.IsWhiteSpace(chr)) { removeWhitespace = false; } if (!removeWhitespace) { builder.Append(chr); } break; } } } if (name == null) { name = builder.ToString(); } parsed = new FeatureParse(name, parameters.ToArray()); if (parens != 0) { failException = new Exception("Malformed feature definition"); return(false); } } else { parsed = preParsed.Value; } if (!featureTypes.TryGetValue(parsed.Name, out var featureType)) { return(false); } try { if (!(Activator.CreateInstance(featureType) is Feature aFeature)) { failException = new InvalidCastException("Feature type not a subtype of Feature"); return(false); } featureValid = aFeature.Initialize(plugin, parsed.Parameters); feature = aFeature; return(true); } catch (Exception e) { failException = e; return(false); } }
private static void FindMemberCastFailByName(ModelContext ctx, IDataReader dr, InvalidCastException ex) { var text = new StringBuilder(); var ms = ctx.Info.SimpleMembers; foreach (var member in ms) { CheckMemberCast(member, dr[member.Name], text); } if (text.Length > 0) { throw new DataException(text.ToString(), ex); } }
/// <summary> /// Errors the message. /// </summary> /// <param name="functionName">Name of the function.</param> /// <param name="e">The e.</param> /// <returns>System.String.</returns> private static string ErrorMessage(string functionName, InvalidCastException e) => $"{ClassLocation}.{functionName} - {e.Message}";
public void IsTypeReturnsCastObject() { InvalidCastException expected = new InvalidCastException(); InvalidCastException actual = Assert.IsType<InvalidCastException>(expected); Assert.Same(expected, actual); }
public static void Ctor_Empty() { var exception = new InvalidCastException(); ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_INVALIDCAST, validateMessage: false); }
internal static InvalidCastException InvalidCast() { InvalidCastException e = new InvalidCastException(); return(e); }
/// <summary> /// 单播,根据指令,通过反射创建一个对象,返回该处理方, 并默认不传递消息; /// </summary> /// <param name="fullName"></param> /// <param name="name"></param> /// <param name="jsonData"></param> /// <returns></returns> public static bool CreateDispose(JsonData jsonData = null, string name = null) { // 这里因为 IDictionary 的 key 和 value 都是 ICollection ,所以只能这样遍历; if (name == null) { name = jsonData.FirstKey(); } IInstructionDispose dispose = FindDispose(name); if (dispose != null) { return(dispose.Dispose(jsonData)); } // 在组件内部反射响应的类,如果没有找到,不抛异常;进而调用客户端注册的方法; // 可以加一个配置文件,以读取相应的配置文件,找对应的类;TODO // 这里先调用客户端注册的方法; Type type = Type.GetType(fullName + "." + name, false, true); if (type == null) { Func <JsonData, bool> func = CustomFunctionLibrary <JsonData> .GetFunc(name); Action action = CustomFunctionLibrary <JsonData> .GetAction(name); if (func != null) { return(func(jsonData)); } if (action != null) { action(); return(true); } #if UNITY_EDITOR throw new NullReferenceException("没有找到指定的类"); #endif return(false); // 不抛异常 } try { dispose = ((IInstructionDispose)type.Assembly.CreateInstance(type.FullName, true)); } catch (InvalidCastException e) { e = new InvalidCastException("没有继承 CommandDisposeBase 类"); throw e; } dicts.Add(name, dispose); return(dispose.Dispose(jsonData)); }
public void ExecuteTestGeneric(object sender, object target) { var testContent1 = new InvalidOperationException(); var testContent2 = new InvalidCastException(); Exception receivedContent1 = null; Exception receivedContent2 = null; object receivedSender = null; object receivedTarget = null; Messenger.Reset(); Messenger.Default.Register <CommandMessage <Exception> >(this, m => { receivedSender = m.Sender; receivedTarget = m.Target; if (m.Command == DummyCommand1) { receivedContent1 = testContent1; return; } if (m.Command == DummyCommand2) { receivedContent2 = testContent2; return; } }); Assert.AreEqual(null, receivedContent1); Assert.AreEqual(null, receivedContent2); CommandMessage <Exception> commandMessage1; CommandMessage <Exception> commandMessage2; if (sender == null) { commandMessage1 = new CommandMessage <Exception>(testContent1, DummyCommand1); commandMessage2 = new CommandMessage <Exception>(testContent2, DummyCommand2); } else { if (target == null) { commandMessage1 = new CommandMessage <Exception>(sender, testContent1, DummyCommand1); commandMessage2 = new CommandMessage <Exception>(sender, testContent2, DummyCommand2); } else { commandMessage1 = new CommandMessage <Exception>(sender, target, testContent1, DummyCommand1); commandMessage2 = new CommandMessage <Exception>(sender, target, testContent2, DummyCommand2); } } Messenger.Default.Send(commandMessage1); Assert.AreEqual(sender, receivedSender); Assert.AreEqual(target, receivedTarget); Assert.AreEqual(testContent1, receivedContent1); Assert.AreEqual(null, receivedContent2); receivedSender = null; receivedTarget = null; Messenger.Default.Send(commandMessage2); Assert.AreEqual(sender, receivedSender); Assert.AreEqual(target, receivedTarget); Assert.AreEqual(testContent1, receivedContent1); Assert.AreEqual(testContent2, receivedContent2); }
public void MatchingType() { var expected = new InvalidCastException(); Assert.IsType(typeof(InvalidCastException), expected); }
public void BaseType() { var expected = new InvalidCastException(); Assert.IsAssignableFrom(typeof(Exception), expected); }
public void MatchingType() { var expected = new InvalidCastException(); Assert.IsType <InvalidCastException>(expected); }
public void SameType() { var expected = new InvalidCastException(); Assert.IsAssignableFrom <InvalidCastException>(expected); }
public void UnmatchedType() { var expected = new InvalidCastException(); Assert.IsNotType(typeof(Exception), expected); }
public void Model_InvalidCast() { InvalidCastException ex = Assert.Throws <InvalidCastException>(() => Function.Model <Models.WrongModel>("public.return_model", null, this.Common.ConnectionString)); Assert.NotNull(ex); }
private bool ExceptionFromDynamicReflection(InvalidCastException e) { return(e.TargetSite.DeclaringType.FullName.IndexOf(DynamicReflectionManager.ASSEMBLY_NAME) >= 0); }
static internal InvalidCastException InvalidCast(string error, Exception inner) { InvalidCastException e = new InvalidCastException(error, inner); return(e); }
public void UnmatchedType() { InvalidCastException expected = new InvalidCastException(); Assert.IsNotType(typeof(Exception), expected); }
public void TestSimple() { var cause = new InvalidCastException(); Assert.Throws <RabbitRejectAndDontRequeueException>(() => DoTest(cause)); }
public void MatchingType() { InvalidCastException expected = new InvalidCastException(); Assert.IsType<InvalidCastException>(expected); }
/// <summary> /// Initializes the command's request object. /// </summary> /// <param name="cmdletInformation"> /// The information about the cmdlet. /// </param> /// <exception cref="CmdletInvocationException"> /// If the constructor for the cmdlet threw an exception. /// </exception> /// <exception cref="MemberAccessException"> /// The type referenced by <paramref name="cmdletInformation"/> refered to an /// abstract type or them member was invoked via a late-binding mechanism. /// </exception> /// <exception cref="TypeLoadException"> /// If <paramref name="cmdletInformation"/> refers to a type that is invalid. /// </exception> private void Init(CmdletInfo cmdletInformation) { Diagnostics.Assert(cmdletInformation != null, "Constructor should throw exception if LookupCommand returned null."); Cmdlet newCmdlet = null; Exception initError = null; string errorIdAndResourceId = null; string resourceStr = null; try { // Create the request object newCmdlet = ConstructInstance(cmdletInformation.ImplementingType); if (newCmdlet == null) { // We could test the inheritance before constructing, but that's // expensive. Much cheaper to just check for null. initError = new InvalidCastException(); errorIdAndResourceId = "CmdletDoesNotDeriveFromCmdletType"; resourceStr = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType; } } catch (MemberAccessException memberAccessException) { initError = memberAccessException; } catch (TypeLoadException typeLoadException) { initError = typeLoadException; } catch (Exception e) // Catch-all OK, 3rd party callout. { // We don't have a Command or InvocationInfo at this point, // since the command failed to initialize. var commandException = new CmdletInvocationException(e, null); // Log a command health event MshLog.LogCommandHealthEvent( this._context, commandException, Severity.Warning); throw commandException; } if (initError != null) { // Log a command health event MshLog.LogCommandHealthEvent( this._context, initError, Severity.Warning); CommandNotFoundException exception = new CommandNotFoundException( cmdletInformation.Name, initError, errorIdAndResourceId ?? "CmdletNotFoundException", resourceStr ?? DiscoveryExceptions.CmdletNotFoundException, initError.Message); throw exception; } this.Command = newCmdlet; this.CommandScope = Context.EngineSessionState.CurrentScope; InitCommon(); }
public void MatchingType() { InvalidCastException expected = new InvalidCastException(); Assert.IsType(typeof(InvalidCastException), expected); }
/// <summary> /// Initializes the command's request object /// </summary> /// /// <param name="cmdletInformation"> /// The information about the cmdlet. /// </param> /// /// <exception cref="CmdletInvocationException"> /// If the constructor for the cmdlet threw an exception. /// </exception> /// /// <exception cref="MemberAccessException"> /// The type referenced by <paramref name="cmdletInformation"/> refered to an /// abstract type or them member was invoked via a late-binding mechanism. /// </exception> /// /// <exception cref="TypeLoadException"> /// If <paramref name="cmdletInformation"/> refers to a type that is invalid. /// </exception> /// private void Init(CmdletInfo cmdletInformation) { Diagnostics.Assert(cmdletInformation != null, "Constructor should throw exception if LookupCommand returned null."); Cmdlet newCmdlet = null; Exception initError = null; string errorIdAndResourceId = null; string resourceStr = null; try { // Create the request object newCmdlet = ConstructInstance(cmdletInformation.ImplementingType); if (newCmdlet == null) { // We could test the inheritance before constructing, but that's // expensive. Much cheaper to just check for null. initError = new InvalidCastException(); errorIdAndResourceId = "CmdletDoesNotDeriveFromCmdletType"; resourceStr = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType; } } catch (MemberAccessException memberAccessException) { initError = memberAccessException; } catch (TypeLoadException typeLoadException) { initError = typeLoadException; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); // We don't have a Command or InvocationInfo at this point, // since the command failed to initialize. var commandException = new CmdletInvocationException(e, null); // Log a command health event MshLog.LogCommandHealthEvent( this._context, commandException, Severity.Warning); throw commandException; } if (null != initError) { // Log a command health event MshLog.LogCommandHealthEvent( this._context, initError, Severity.Warning); CommandNotFoundException exception = new CommandNotFoundException( cmdletInformation.Name, initError, errorIdAndResourceId ?? "CmdletNotFoundException", resourceStr ?? DiscoveryExceptions.CmdletNotFoundException, initError.Message); throw exception; } this.Command = newCmdlet; this.CommandScope = Context.EngineSessionState.CurrentScope; InitCommon(); }
public void IsNotType() { InvalidCastException expected = new InvalidCastException(); Assert.IsNotType(typeof(Exception), expected); Assert.IsNotType<Exception>(expected); }
internal ConnectionPointCookie(object source, object sink, Type eventInterface) { Exception ex = null; if (source is UnsafeNativeMethods.IConnectionPointContainer) { UnsafeNativeMethods.IConnectionPointContainer cpc = (UnsafeNativeMethods.IConnectionPointContainer)source; try { Guid tmp = eventInterface.GUID; if (cpc.FindConnectionPoint(ref tmp, out connectionPoint) != NativeMethods.S_OK) { connectionPoint = null; } } catch (Exception e) { if (CriticalExceptions.IsCriticalException(e)) { throw; } connectionPoint = null; } if (connectionPoint == null) { ex = new ArgumentException(SR.Get(SRID.AxNoEventInterface, eventInterface.Name)); } // IsComObject(sink): this is the case of a managed sink object wrapped in IDispatchSTAForwarder - // see WebBrowser.CreateSink(). else if (sink == null || !eventInterface.IsInstanceOfType(sink) && !Marshal.IsComObject(sink)) { ex = new InvalidCastException(SR.Get(SRID.AxNoSinkImplementation, eventInterface.Name)); } else { int hr = connectionPoint.Advise(sink, ref cookie); if (hr != NativeMethods.S_OK) { cookie = 0; Marshal.FinalReleaseComObject(connectionPoint); connectionPoint = null; ex = new InvalidOperationException(SR.Get(SRID.AxNoSinkAdvise, eventInterface.Name, hr)); } } } else { ex = new InvalidCastException(SR.Get(SRID.AxNoConnectionPointContainer)); } if (connectionPoint == null || cookie == 0) { if (connectionPoint != null) { Marshal.FinalReleaseComObject(connectionPoint); } if (ex == null) { throw new ArgumentException(SR.Get(SRID.AxNoConnectionPoint, eventInterface.Name)); } else { throw ex; } } }
//Evento de carga del formulario principal private void FormPrincipal_Load(object sender, EventArgs e) { InvalidCastException icEx = new InvalidCastException(); try { creaDataset(); } catch { MessageBox.Show("In order to use this app your SQL must be active" + Environment.NewLine + "The program will now close"); this.Close(); } try { //INICIO foreach (DataTable dt in ds.Tables) { if (dt.TableName.Equals("Artists")) { foreach (DataRow dr in dt.Rows) { if (dr.IsNull("Genre") || dr.IsNull("Labels") || dr.IsNull("RealName")) { throw icEx; } addedArtist = new Artist(dr[0] + "", dr[1] + "", dr[2] + "", dr[3] + ""); artists.Add(addedArtist); lbArtist.Items.Add(addedArtist.Name); } } if (dt.TableName.Equals("Albums")) { foreach (DataRow dr in dt.Rows) { if (dr.IsNull("ReleaseMonth") || dr.IsNull("ReleaseCountry") || dr.IsNull("RecordLabel") || dr.IsNull("Genre") || dr.IsNull("AlbumArtist")) { throw icEx; } addedAlbum = new Album(dr[0] + "", Convert.ToInt32(dr[1]), dr[2] + "", Convert.ToInt32(dr[3]), dr[4] + "", dr[5] + "", dr[6] + "", Convert.ToInt32(dr[7]), Convert.ToInt32(dr[8]), dr[9] + ""); albums.Add(addedAlbum); lbAlbum.Items.Add(addedAlbum.Title); } } if (dt.TableName.Equals("Songs")) { foreach (DataRow dr in dt.Rows) { if (dr.IsNull("Album") || dr.IsNull("Artist") || dr.IsNull("Genre")) { throw icEx; } addedSong = new Song(dr[0] + "", dr[1] + "", dr[2] + "", Convert.ToInt32(dr[3]), Convert.ToInt32(dr[4]), dr[5] + ""); songs.Add(addedSong); lbSong.Items.Add(addedSong.SongName); } } } } catch (System.InvalidCastException icExG) { MessageBox.Show("Your database can't contain NULL values, the program will now finish"); this.Close(); } this.Refresh(); }
public void IsAssignableFrom_BaseType() { var expected = new InvalidCastException(); Assert.IsAssignableFrom(typeof(Exception), expected); Assert.IsAssignableFrom<Exception>(expected); }
public InvalidCast_Exception(InvalidCastException ex) : base(ex.Message, ex) { LoggerConfiguration.DefaultSetup(); this.LoggerException(); }
/// <include file='doc\NativeMethods.uex' path='docs/doc[@for="NativeMethods.ConnectionPointCookie.ConnectionPointCookie1"]/*' /> /// <devdoc> /// Creates a connection point to of the given interface type. /// which will call on a managed code sink that implements that interface. /// </devdoc> public ConnectionPointCookie(object source, object sink, Type eventInterface, bool throwException, out bool connected){ connected = false; Exception ex = null; if (source is UnsafeNativeMethods.IConnectionPointContainer) { UnsafeNativeMethods.IConnectionPointContainer cpc = (UnsafeNativeMethods.IConnectionPointContainer)source; try { Guid tmp = eventInterface.GUID; if (cpc.FindConnectionPoint(ref tmp, out connectionPoint) != NativeMethods.S_OK) { connectionPoint = null; } } catch (Exception) { connectionPoint = null; } if (connectionPoint == null) { ex = new ArgumentException(SR.GetString(SR.ConnPointSourceIF, eventInterface.Name )); } else if (sink == null || !eventInterface.IsInstanceOfType(sink)) { ex = new InvalidCastException(SR.GetString(SR.ConnPointSinkIF)); } else { int hr = connectionPoint.Advise(sink, ref cookie); if (hr != S_OK) { cookie = 0; Marshal.ReleaseComObject(connectionPoint); connectionPoint = null; ex = new ExternalException(SR.GetString(SR.ConnPointAdviseFailed, eventInterface.Name, hr )); } else { connected = true; } } } else { ex = new InvalidCastException(SR.GetString(SR.ConnPointSourceIF, "IConnectionPointContainer")); } if (throwException && (connectionPoint == null || cookie == 0)) { if (connectionPoint != null) { Marshal.ReleaseComObject(connectionPoint); } if (ex == null) { throw new ArgumentException(SR.GetString(SR.ConnPointCouldNotCreate, eventInterface.Name )); } else { throw ex; } } #if DEBUG new EnvironmentPermission(PermissionState.Unrestricted).Assert(); try { callStack = Environment.StackTrace; } finally { System.Security.CodeAccessPermission.RevertAssert(); } #endif }
static internal InvalidCastException InvalidCast(string error, Exception inner) { InvalidCastException e = new InvalidCastException(error, inner); return e; }
static internal Exception ParameterConversionFailed(object value, Type destType, Exception inner) { Debug.Assert(null != value, "null value on conversion failure"); Debug.Assert(null != inner, "null inner on conversion failure"); Exception e; string message = Res.GetString(Res.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); if (inner is ArgumentException) { e = new ArgumentException(message, inner); } else if (inner is FormatException) { e = new FormatException(message, inner); } else if (inner is InvalidCastException) { e = new InvalidCastException(message, inner); } else if (inner is OverflowException) { e = new OverflowException(message, inner); } else { e = inner; } return e; }
private static void FindMemberCastFailByIndex(ModelContext ctx, IDataReader dr, InvalidCastException ex) { var text = new StringBuilder(); var ms = ctx.Info.SimpleMembers; for (int i = 0; i < ms.Length; i++) { CheckMemberCast(ms[i], dr[i], text); } if (text.Length > 0) { throw new DataException(text.ToString(), ex); } }
public void SameType() { var expected = new InvalidCastException(); Assert.IsAssignableFrom(typeof(InvalidCastException), expected); }
private InvalidCastException _excepcion; //Tipo de excepcion que se genero. public CasteoNoCorrectoException(InvalidCastException excepcion, string mensaje) { _fecha = DateTime.Now; _mensaje = mensaje; _excepcion = excepcion; }
static internal InvalidCastException InvalidCast() { InvalidCastException e = new InvalidCastException(); return e; }
/// <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 = ConstructExceptionUsingReflection( "System.Runtime.Serialization.SerializationException, System.Runtime.Serialization.Primitives, Version=4.0.0.0", 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:X}", SR.Excep_FromHResult, errorCode); 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); }
public void IsAssignableFrom_SameType() { InvalidCastException expected = new InvalidCastException(); Assert.IsAssignableFrom(typeof(InvalidCastException), expected); Assert.IsAssignableFrom<InvalidCastException>(expected); }
public void UnmatchedType() { InvalidCastException expected = new InvalidCastException(); Assert.IsNotType <Exception>(expected); }