/// <summary> /// Creates a connection point to of the given interface type /// which will call on a managed code sink that implements that interface. /// </summary> public ConnectionPointCookie(object source, object sink, Type eventInterface, bool throwException) { Exception ex = null; if (source is IConnectionPointContainer) { _connectionPointContainer = (IConnectionPointContainer)source; try { Guid tmp = eventInterface.GUID; _connectionPointContainer.FindConnectionPoint(ref tmp, out _connectionPoint); } catch { _connectionPoint = null; } if (_connectionPoint == null) { ex = new NotSupportedException(); } else if (sink == null || !eventInterface.IsInstanceOfType(sink)) { ex = new InvalidCastException(); } else { try { _connectionPoint.Advise(sink, out _cookie); } catch { _cookie = 0; _connectionPoint = null; ex = new Exception(); } } } else { ex = new InvalidCastException(); } if (throwException && (_connectionPoint == null || _cookie == 0)) { Dispose(); if (ex == null) { throw new ArgumentException("Exception null, but cookie was zero or the connection point was null"); } else { throw ex; } } #if DEBUG //_callStack = Environment.StackTrace; //this._eventInterface = eventInterface; #endif }
public void Relay() { Class1 c1 = new Class1(); try { c1.Display(); } //processing an exception catch (MyCustomException e) { Console.WriteLine("exception partially handled - rethrowing it up the call stack"); //throw; //i encounter a new exception InvalidCastException ice = new InvalidCastException("inner exception - nash"); try { throw ice; } catch (Exception e1) { throw new MyCustomException("new exception occurred", ice, DateTime.Now); } } }
static unsafe MonoObject *CreateException(ExceptionType type, IntPtr arg0) { Exception rv = null; var str0 = Marshal.PtrToStringAuto(arg0); switch (type) { case ExceptionType.System_Exception: rv = new System.Exception(str0); break; case ExceptionType.System_InvalidCastException: rv = new System.InvalidCastException(str0); break; case ExceptionType.System_EntryPointNotFoundException: rv = new System.EntryPointNotFoundException(str0); break; case ExceptionType.System_OutOfMemoryException: rv = new System.OutOfMemoryException(); break; default: throw new ArgumentOutOfRangeException(nameof(type)); } return((MonoObject *)GetMonoObject(rv)); }
public void ConstructorWithMessageAndInnerExceptionWorks() { var inner = new Exception("a"); var ex = new InvalidCastException("The message", inner); Assert.IsTrue((object)ex is InvalidCastException, "is InvalidCastException"); Assert.IsTrue(ReferenceEquals(ex.InnerException, inner), "InnerException"); Assert.AreEqual(ex.Message, "The message"); }
public void TestWarningLog() { Exception ex = new InvalidCastException(); bool saved = Log.LogWarning(ex, "LoggerTest"); Assert.AreEqual<bool>(saved, true); }
private static System.InvalidCastException CreateExceptionForInvalidCast( PropertyType type, PropertyType unboxType) { System.InvalidCastException ex = new System.InvalidCastException(SR.Format(SR.PropertyValue_InvalidCast, type, unboxType)); McgMarshal.SetExceptionErrorCode(ex, Interop.COM.TYPE_E_TYPEMISMATCH); return(ex); }
public void TypePropertiesAreCorrect() { Assert.AreEqual(typeof(InvalidCastException).FullName, "ss.InvalidCastException", "Name"); Assert.IsTrue(typeof(InvalidCastException).IsClass, "IsClass"); Assert.AreEqual(typeof(InvalidCastException).BaseType, typeof(Exception), "BaseType"); object d = new InvalidCastException(); Assert.IsTrue(d is InvalidCastException, "is InvalidCastException"); Assert.IsTrue(d is Exception, "is Exception"); var interfaces = typeof(InvalidCastException).GetInterfaces(); Assert.AreEqual(interfaces.Length, 0, "Interfaces length"); }
public void DoWorkStateShouldBeCompletedWithExceptionWhenExceptionOccurs() { Exception invalidCastException = new InvalidCastException(); WorkItemBase workItemBase = Substitute.ForPartsOf<WorkItemBase>(); workItemBase.When(x => x.DoWorkInternal()).Do( x => { throw invalidCastException; }); workItemBase.DoWork(); Assert.AreEqual(WorkItemState.CompletedWithException, workItemBase.State); Assert.AreSame(invalidCastException, workItemBase.LastException); }
public void TargetThrowsInvalidCastException() { Exception expectedException = new InvalidCastException(); ITestObject test1 = (ITestObject)factory.GetObject("test1"); try { test1.Exceptional(expectedException); Assert.Fail("Should have thrown exception raised by target"); } catch (Exception ex) { Assert.AreEqual(expectedException, ex, "exception matches"); Assert.AreEqual(1, test1.ExceptionMethodCallCount); } }
public object MakeIntoType(string valueBeingCast, Type typeBeingCastTo) { try { var defs = transforms.Where(x => x.ReturnType == typeBeingCastTo && x.Regex.Match(valueBeingCast).Success); if (defs.Any()) return new TransformCaller(defs.First(), this).Call(valueBeingCast); if (typeBeingCastTo == typeof(string)) return valueBeingCast; if (typeBeingCastTo == typeof(Int32)) return Int32.Parse(valueBeingCast); if (typeBeingCastTo == typeof(Int64)) return Int64.Parse(valueBeingCast); if (typeBeingCastTo == typeof(double)) return double.Parse(valueBeingCast); if (typeBeingCastTo == typeof(decimal)) return decimal.Parse(valueBeingCast); if (typeBeingCastTo == typeof(float)) return float.Parse(valueBeingCast); if (typeBeingCastTo == typeof(DateTime)) return DateTime.Parse(valueBeingCast); if (typeBeingCastTo == typeof(bool)) return bool.Parse(valueBeingCast); if (typeBeingCastTo == typeof(Guid)) return new Guid(valueBeingCast); } catch (Exception ex) { var message = "Unable to convert: \"" + valueBeingCast + "\" into a " + typeBeingCastTo.Name; var newException = new InvalidCastException(message); throw new InvalidCastException(message, newException); } throw new InvalidCastException("Don't know how to convert: \"" + valueBeingCast + "\" into a " + typeBeingCastTo.Name); }
/// <summary> /// Invokes the specified input. /// </summary> /// <param name="input">The input.</param> /// <param name="getNext">The get next.</param> /// <returns></returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { Exception ex = null; if (input.Inputs.Count != 1) { ex = new ArgumentOutOfRangeException("Action methods can only contains one argument!"); } if (input.Inputs[0].GetType() != typeof(string[])) { ex = new ArgumentException("The action method argument must be of type string[]!"); } if (Length > -1) { var arg = (string[])input.Arguments[0]; if (arg.Length != Length) { ex = new ArgumentOutOfRangeException("Invalid number of arguments!"); } } var types = input.MethodBase.GetCustomAttributes(typeof(ArgumentTypeAttribute), true); if (types != null && types.Count() > 0) { foreach (var tp in types.Cast<ArgumentTypeAttribute>()) { try { Convert.ChangeType(input.Arguments[tp.Index], tp.Type); } catch (InvalidCastException) { ex = new InvalidCastException(string.Format("The argument index: {0} must be of type: {1}!", tp.Index, tp.Type.ToString())); } } } return ex != null ? input.CreateExceptionMethodReturn(ex) : getNext()(input, getNext); }
private void Init(CmdletInfo cmdletInformation) { Cmdlet cmdlet = null; Exception exception = null; string str = null; string cmdletDoesNotDeriveFromCmdletType = null; try { cmdlet = ConstructInstance(cmdletInformation.ImplementingType); if (cmdlet == null) { exception = new InvalidCastException(); str = "CmdletDoesNotDeriveFromCmdletType"; cmdletDoesNotDeriveFromCmdletType = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType; } } catch (MemberAccessException exception2) { exception = exception2; } catch (TypeLoadException exception3) { exception = exception3; } catch (Exception exception4) { CommandProcessorBase.CheckForSevereException(exception4); CmdletInvocationException exception5 = new CmdletInvocationException(exception4, null); MshLog.LogCommandHealthEvent(base._context, exception5, Severity.Warning); throw exception5; } if (exception != null) { MshLog.LogCommandHealthEvent(base._context, exception, Severity.Warning); CommandNotFoundException exception6 = new CommandNotFoundException(cmdletInformation.Name, exception, str ?? "CmdletNotFoundException", cmdletDoesNotDeriveFromCmdletType ?? DiscoveryExceptions.CmdletNotFoundException, new object[] { exception.Message }); throw exception6; } base.Command = cmdlet; base.CommandScope = base.Context.EngineSessionState.CurrentScope; this.InitCommon(); }
// (Integer, "3") return object of new Integer(3) public object Parse(Type c, string s) { Type d = ReflectionUtilities.BoxClass(c); foreach (Type e in ReflectionUtilities.ClassAndAncestors(d)) { // get all the super classes of Integer for example string name = ReflectionUtilities.GetAssemblyQualifiedName(e); if (parsers.ContainsKey(name)) { object ret = Parse(name, s); // check if ret can be cast as c if (c.IsAssignableFrom(ret.GetType())) { return ret; } else { var ex = new InvalidCastException("Cannot cast from " + ret.GetType() + " to " + c); Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER); } } } return Parse(d.Name, s); }
public void IsType() { InvalidCastException expected = new InvalidCastException(); Assert.IsType(typeof(InvalidCastException), expected); Assert.IsType<InvalidCastException>(expected); }
public void IsTypeReturnsCastObject() { InvalidCastException expected = new InvalidCastException(); InvalidCastException actual = Assert.IsType<InvalidCastException>(expected); Assert.Same(expected, actual); }
public ConnectionPointCookie(object source, object sink, System.Type eventInterface, bool throwException) { Exception exception1 = null; if (source is Microsoft.VisualStudio.OLE.Interop.IConnectionPointContainer) { this.cpc = (Microsoft.VisualStudio.OLE.Interop.IConnectionPointContainer) source; try { Guid guid1 = eventInterface.GUID; this.cpc.FindConnectionPoint(ref guid1, out this.connectionPoint); } catch { this.connectionPoint = null; } if (this.connectionPoint == null) { exception1 = new ArgumentException(); goto Label_009A; } if ((sink == null) || !eventInterface.IsInstanceOfType(sink)) { exception1 = new InvalidCastException(); goto Label_009A; } try { this.connectionPoint.Advise(sink, out this.cookie); goto Label_009A; } catch { this.cookie = 0; this.connectionPoint = null; exception1 = new Exception(); goto Label_009A; } } exception1 = new InvalidCastException(); Label_009A: if (!throwException || ((this.connectionPoint != null) && (this.cookie != 0))) { return; } if (exception1 == null) { throw new ArgumentException(); } throw exception1; }
public void SendMails(IDaoFactory daoFactory) { try { var deliveryToSend = daoFactory.GetDeliveryPoDao().GetDeliveryToSend(); if (deliveryToSend != null && !SendingDeliveryId.Contains(deliveryToSend.Id)) { initialize(deliveryToSend.SenderEmail == ConfigurationManager.AppSettings["MailFrom"] ? null : daoFactory.GetAziendaDao().GetById(deliveryToSend.IdAzienda, false)); if (deliveryToSend.AttemptNumber >= deliveryToSend.MaxRetry) { deliveryToSend.State = StatoDelivery.Bloccato; daoFactory.GetDeliveryPoDao().SaveOrUpdate(deliveryToSend); SendingDeliveryId.Remove(deliveryToSend.Id); deliveryToSend = daoFactory.GetDeliveryPoDao().GetDeliveryToSend(); } if (deliveryToSend != null && !SendingDeliveryId.Contains(deliveryToSend.Id)) { var log = new DeliveryLog(deliveryToSend, $"Iniziato l'invio della spedizione di tipo '{deliveryToSend.Type}' - #{deliveryToSend.Id}"); deliveryToSend.AttemptNumber++; SendingDeliveryId.Add(deliveryToSend.Id); deliveryToSend.State = StatoDelivery.InSpedizione; var retryIndex = 0; bool allSented; // Finchè tutte le mail sono spedite oppure viene raggiunto il numero massimo di tentativi cerco di spedire tutte le mail accodate do { allSented = true; var index = 0; foreach (var deliveryMessage in deliveryToSend.Messages) { var deliveryMessagePo = deliveryMessage as DeliveryMessagePo; if (deliveryMessagePo != null) { if (deliveryMessagePo.SendingDate == null) { var sendArgs = SendMail(deliveryMessagePo); if (sendArgs.Exception == null) { deliveryMessagePo.SendingDate = DateTime.Now; deliveryMessagePo.Smtp = sendArgs.Smtp; deliveryMessagePo.AttemptNumber = retryIndex; } else { deliveryMessagePo.Exception += sendArgs.Exception.Message; allSented = false; } index++; // Attesa prima di spedire la nuova mail if(deliveryToSend.Messages.Count > index) Thread.Sleep(5000); } } else { var fatalException = new InvalidCastException($"Fallito il cast di un oggetto DeliveryMessage a DeliveryMessagePo#{deliveryMessage.Id}"); _log.FatalFormat("Fallito il cast di un oggetto DeliveryMessage", fatalException); throw fatalException; } } retryIndex++; } while (!allSented && retryIndex < deliveryToSend.MaxRetry); if (allSented) deliveryToSend.State = StatoDelivery.Spedito; deliveryToSend.EndSendingDate = DateTime.Now; SendingDeliveryId.Remove(deliveryToSend.Id); daoFactory.GetDeliveryPoDao().SaveOrUpdate(deliveryToSend); var logFine = new DeliveryLog(deliveryToSend, string.Format("Finito l'invio della spedizione di tipo '{0}' - Sono stati elaborati {2} messaggi ({3} non inviati per errori) - #{1}", deliveryToSend.Type, deliveryToSend.Id, deliveryToSend.Messages.Count, deliveryToSend.Messages.Cast<DeliveryMessagePo>().Count(item => item.SendingDate == null))); daoFactory.GetDeliveryLogDao().SaveOrUpdate(logFine); } } daoFactory.GetDeliveryPoDao().CommitChanges(); } catch (Exception ex) { _log.FatalFormat("Invio non riuscito - {0}", ex, Library.Utility.GetMethodDescription()); } finally { SendingDeliveryId.Clear(); } }
protected override ListViewItem ConstruirListView(ISaquinho saquinho) { ListViewItem item; SaquinhoHistóricoRelacionado saquinhoRelacionado; saquinhoRelacionado = (saquinho as SaquinhoHistóricoRelacionado); if (saquinhoRelacionado == null) { Exception erro; if (saquinho == null) erro = new NullReferenceException("O saquinho não pode ser nulo"); else erro = new InvalidCastException("O saquinho não é do tipo saquinhoRelacionado"); throw erro; } item = base.ConstruirListView(saquinho); item.SubItems[colData.Index].Text = saquinhoRelacionado.Data.ToString(); if (saquinhoRelacionado.Funcionário != null) item.SubItems[colFuncionário.Index].Text = saquinhoRelacionado.Funcionário.Nome; item.SubItems[colAção.Index].Text = saquinhoRelacionado.Tipo == SaquinhoHistóricoRelacionado.TipoEnum.Removeu ? "Excluíu" : "Relacionou"; if (saquinhoRelacionado.Tipo == SaquinhoHistóricoRelacionado.TipoEnum.Removeu) { item.ForeColor = Color.White; item.BackColor = Color.Red; item.UseItemStyleForSubItems = true; } return item; }
/// <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; }
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<NotificationMessage<Exception>>( this, m => { receivedSender = m.Sender; receivedTarget = m.Target; if (m.Notification == DummyNotification1) { receivedContent1 = testContent1; return; } if (m.Notification == DummyNotification2) { receivedContent2 = testContent2; return; } }); Assert.AreEqual(null, receivedContent1); Assert.AreEqual(null, receivedContent2); NotificationMessage<Exception> message1; NotificationMessage<Exception> message2; if (sender == null) { message1 = new NotificationMessage<Exception>(testContent1, DummyNotification1); message2 = new NotificationMessage<Exception>(testContent2, DummyNotification2); } else { if (target == null) { message1 = new NotificationMessage<Exception>(sender, testContent1, DummyNotification1); message2 = new NotificationMessage<Exception>(sender, testContent2, DummyNotification2); } else { message1 = new NotificationMessage<Exception>(sender, target, testContent1, DummyNotification1); message2 = new NotificationMessage<Exception>(sender, target, testContent2, DummyNotification2); } } Messenger.Default.Send(message1); Assert.AreEqual(sender, receivedSender); Assert.AreEqual(target, receivedTarget); Assert.AreEqual(testContent1, receivedContent1); Assert.AreEqual(null, receivedContent2); receivedSender = null; receivedTarget = null; Messenger.Default.Send(message2); Assert.AreEqual(sender, receivedSender); Assert.AreEqual(target, receivedTarget); Assert.AreEqual(testContent1, receivedContent1); Assert.AreEqual(testContent2, receivedContent2); }
internal static string UnregisteredTypeEventArgsRegisterDelegateReturnedUncastableInstance( Type serviceType, InvalidCastException exception) => string.Format(CultureInfo.InvariantCulture, "The delegate that was registered for service type {0} using the {2}.{3}(Func<object>) " + "method returned an object that couldn't be casted to {0}. {1}", serviceType.ToFriendlyName(), exception.Message, nameof(UnregisteredTypeEventArgs), nameof(UnregisteredTypeEventArgs.Register));
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; } } }
public ConnectionPointCookie(object source, object sink, Type eventInterface, bool throwException) { Exception ex = null; if (source is NativeMethods.IConnectionPointContainer) { NativeMethods.IConnectionPointContainer cpc = (NativeMethods.IConnectionPointContainer)source; try { Guid tmp = eventInterface.GUID; cpc.FindConnectionPoint(ref tmp, out connectionPoint); } catch(Exception) { connectionPoint = null; } if (connectionPoint == null) { ex = new ArgumentException("The source object does not expose the " + eventInterface.Name + " event inteface"); } else if (!eventInterface.IsInstanceOfType(sink)) { ex = new InvalidCastException("The sink object does not implement the eventInterface"); } else { try { connectionPoint.Advise(sink, out cookie); } catch { cookie = 0; connectionPoint = null; ex = new Exception("IConnectionPoint::Advise failed for event interface '" + eventInterface.Name + "'"); } } } else { ex = new InvalidCastException("The source object does not expost IConnectionPointContainer"); } if (throwException && (connectionPoint == null || cookie == 0)) { if (ex == null) { throw new ArgumentException("Could not create connection point for event interface '" + eventInterface.Name + "'"); } else { throw ex; } } }
public void DoWorkShouldSetLastExceptionWhenExceptionOccurs() { Exception invalidCastException = new InvalidCastException(); WorkItemBase workItemBase = Substitute.ForPartsOf<WorkItemBase>(); workItemBase.When(x => x.DoWorkInternal()).Do( x => { throw invalidCastException; }); workItemBase.DoWork(); Assert.AreSame(invalidCastException, workItemBase.LastException); }
internal void SetResponse(MessageReceivedEventArgs e) { object param = null; try { if (e.MessageData != null && e.MessageData.Length > 0) param = SerializeHelper.DeserializeFromBytes(e.MessageData, ResultType); else e.IsError = IsRequired; } catch (Exception ex) { IsError = true; Exception = new InvalidCastException("Ошибка разбора результата, или результат имеет тип отличный от указанного.", ex); } Result = param; IsResponse = true; Wait.Set(); }
public async Task InvokeAction_ExceptionInAuthorizationFilterCannotBeHandledByOtherFilters() { // Arrange var expected = new InvalidCastException(); var exceptionFilter = new Mock<IExceptionFilter>(MockBehavior.Strict); exceptionFilter .Setup(f => f.OnException(It.IsAny<ExceptionContext>())) .Callback<ExceptionContext>(context => { // Mark as handled context.Result = new EmptyResult(); }) .Verifiable(); var authorizationFilter1 = new Mock<IAuthorizationFilter>(MockBehavior.Strict); authorizationFilter1 .Setup(f => f.OnAuthorization(It.IsAny<AuthorizationContext>())) .Callback<AuthorizationContext>(c => { throw expected; }) .Verifiable(); // None of these filters should run var authorizationFilter2 = new Mock<IAuthorizationFilter>(MockBehavior.Strict); var resourceFilter = new Mock<IResourceFilter>(MockBehavior.Strict); var actionFilter = new Mock<IActionFilter>(MockBehavior.Strict); var resultFilter = new Mock<IResultFilter>(MockBehavior.Strict); var invoker = CreateInvoker(new IFilterMetadata[] { exceptionFilter.Object, authorizationFilter1.Object, authorizationFilter2.Object, resourceFilter.Object, actionFilter.Object, resultFilter.Object, }); // Act var thrown = await Assert.ThrowsAsync<InvalidCastException>(invoker.InvokeAsync); // Assert Assert.Same(expected, thrown); exceptionFilter.Verify(f => f.OnException(It.IsAny<ExceptionContext>()), Times.Never()); authorizationFilter1.Verify(f => f.OnAuthorization(It.IsAny<AuthorizationContext>()), Times.Once()); }
public virtual ProcessEngineException configurationClassHasWrongType(string className, Type expectedType, System.InvalidCastException e) { //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method: return(new ProcessEngineException(exceptionMessage("032", "Class '{}' has wrong type. Must extend {}", expectedType.FullName), e)); }
/// <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) { Exception ex = null; if (source is IConnectionPointContainer) { cpc = (IConnectionPointContainer)source; try { Guid tmp = eventInterface.GUID; cpc.FindConnectionPoint(ref tmp, out connectionPoint); } catch { connectionPoint = null; } if (connectionPoint == null) { ex = new ArgumentException( /* SR.GetString(SR.ConnectionPoint_SourceIF, eventInterface.Name)*/); } else if (sink == null || !eventInterface.IsInstanceOfType(sink)) { ex = new InvalidCastException( /* SR.GetString(SR.ConnectionPoint_SinkIF)*/); } else { try { connectionPoint.Advise(sink, out cookie); } catch { cookie = 0; connectionPoint = null; ex = new Exception( /*SR.GetString(SR.ConnectionPoint_AdviseFailed, eventInterface.Name)*/); } } } else { ex = new InvalidCastException( /*SR.ConnectionPoint_SourceNotICP)*/); } if (throwException && (connectionPoint == null || cookie == 0)) { if (ex == null) { throw new ArgumentException( /*SR.GetString(SR.ConnectionPoint_CouldNotCreate, eventInterface.Name)*/); } throw ex; } #if DEBUG callStack = Environment.StackTrace; this.eventInterface = eventInterface; #endif }
internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner) { Exception exception; string message = System.Data.Res.GetString("ADP_ParameterConversionFailed", new object[] { value.GetType().Name, destType.Name }); if (inner is ArgumentException) { exception = new ArgumentException(message, inner); } else if (inner is FormatException) { exception = new FormatException(message, inner); } else if (inner is InvalidCastException) { exception = new InvalidCastException(message, inner); } else if (inner is OverflowException) { exception = new OverflowException(message, inner); } else { exception = inner; } TraceExceptionAsReturnValue(exception); return exception; }
//Two helper functions for the two-way conversions between list and string internal static Exception ToList(object value, ref IList list) { Exception e = null; if (value is IList) { list = (IList)value; } else if (value is string) { string strValue = value as string; string[] items = strValue.Split(' '); list = new List<object>(items); } else e = new InvalidCastException(); return e; }
public void DefaultConstructorWorks() { var ex = new InvalidCastException(); Assert.IsTrue((object)ex is InvalidCastException, "is InvalidCastException"); Assert.IsTrue(ex.InnerException == null, "InnerException"); Assert.AreEqual(ex.Message, "The cast is not valid."); }
public ConnectionPointCookie(object source, object sink, Type eventInterface, bool throwException) { Exception exception = null; if (source is UCOMIConnectionPointContainer) { UCOMIConnectionPointContainer container = (UCOMIConnectionPointContainer) source; try { Guid gUID = eventInterface.GUID; container.FindConnectionPoint(ref gUID, out this.connectionPoint); } catch (Exception) { this.connectionPoint = null; } if (this.connectionPoint == null) { exception = new ArgumentException("The source object does not expose the " + eventInterface.Name + " event inteface"); goto Label_00C1; } if (!eventInterface.IsInstanceOfType(sink)) { exception = new InvalidCastException("The sink object does not implement the eventInterface"); goto Label_00C1; } try { this.connectionPoint.Advise(sink, out this.cookie); goto Label_00C1; } catch { this.cookie = 0; this.connectionPoint = null; exception = new Exception("IConnectionPoint::Advise failed for event interface '" + eventInterface.Name + "'"); goto Label_00C1; } } exception = new InvalidCastException("The source object does not expost IConnectionPointContainer"); Label_00C1: if (!throwException || ((this.connectionPoint != null) && (this.cookie != 0))) { return; } if (exception == null) { throw new ArgumentException("Could not create connection point for event interface '" + eventInterface.Name + "'"); } throw exception; }
public void ConstructorWithMessageWorks() { var ex = new InvalidCastException("The message"); Assert.IsTrue((object)ex is InvalidCastException, "is InvalidCastException"); Assert.IsTrue(ex.InnerException == null, "InnerException"); Assert.AreEqual(ex.Message, "The message"); }