private static Exception MapTypeInitializeException(TypeInitializationException t, Type handler) { #if FIRST_PASS return(null); #else bool wrapped = false; Exception r = MapException <Exception>(t.InnerException, true, false); if (!(r is java.lang.Error)) { // Forwarding "r" as cause only doesn't make it available in the debugger details // of current versions of VS, so at least provide a text representation instead. // Not wrapping at all might be the even better approach, but it was introduced for // some reason I guess. r = new java.lang.ExceptionInInitializerError(r.ToString()); wrapped = true; } string type = t.TypeName; if (failedTypes.ContainsKey(type)) { r = new java.lang.NoClassDefFoundError("Could not initialize class " + type); wrapped = true; } if (handler != null && !handler.IsInstanceOfType(r)) { return(null); } failedTypes[type] = type; if (wrapped) { // transplant the stack trace ((Throwable)r).setStackTrace(new ExceptionInfoHelper(t, true).get_StackTrace(t)); } return(r); #endif }
public void FatalityTest() { var nonfatal1 = new ApplicationException("exception1"); var nonfatal2 = new InsufficientMemoryException("Oops"); var fatal1 = new OutOfMemoryException("Oops"); var fatal2 = new DataException(); var fatal3 = new AccessViolationException("Oops"); var fatal4 = new SEHException("Oops"); var fatal5 = new TypeInitializationException("fulltypename", fatal1); var fatal6 = new TargetInvocationException(fatal1); var fatal7 = new AggregateException("Oops", new Exception[] { fatal1, fatal2 }); var fatal8 = new AggregateException("Oops", fatal7); Assert.IsFalse(((Exception)null).IsFatal(), "Null should be non fatal"); Assert.IsFalse(nonfatal1.IsFatal(), "Non fatal 1 expected"); Assert.IsFalse(nonfatal2.IsFatal(), "Non fatal 2 expected"); Assert.IsTrue(fatal1.IsFatal(), "Fatal 1 expected"); Assert.IsTrue(fatal2.IsFatal(), "Fatal 2 expected"); Assert.IsTrue(fatal3.IsFatal(), "Fatal 3 expected"); Assert.IsTrue(fatal4.IsFatal(), "Fatal 4 expected"); Assert.IsTrue(fatal5.IsFatal(), "Fatal 5 expected"); Assert.IsTrue(fatal6.IsFatal(), "Fatal 6 expected"); Assert.IsTrue(fatal7.IsFatal(), "Fatal 7 expected"); Assert.IsTrue(fatal8.IsFatal(), "Fatal 8 expected"); }
private static Exception MapTypeInitializeException(TypeInitializationException t, Type handler) { #if FIRST_PASS return(null); #else bool wrapped = false; Exception r = MapException <Exception>(t.InnerException, true, false); if (!(r is java.lang.Error)) { r = new java.lang.ExceptionInInitializerError(r); wrapped = true; } string type = t.TypeName; if (failedTypes.ContainsKey(type)) { r = new java.lang.NoClassDefFoundError("Could not initialize class " + type); wrapped = true; } if (handler != null && !handler.IsInstanceOfType(r)) { return(null); } failedTypes[type] = type; if (wrapped) { // transplant the stack trace ((Throwable)r).setStackTrace(new ExceptionInfoHelper(t, true).get_StackTrace(t)); } return(r); #endif }
// Test the TypeInitializationException class. public void TestTypeInitializationException() { TypeInitializationException e; e = new TypeInitializationException(null, null); AssertEquals("TypeInitializationException (1)", String.Empty, e.TypeName); AssertNotNull("TypeInitializationException (2)", e.Message); ExceptionTester.CheckHResult ("TypeInitializationException (3)", e, unchecked ((int)0x80131534)); e = new TypeInitializationException("type", null); AssertEquals("TypeInitializationException (4)", "type", e.TypeName); AssertNotNull("TypeInitializationException (5)", e.Message); ExceptionTester.CheckHResult ("TypeInitializationException (6)", e, unchecked ((int)0x80131534)); e = new TypeInitializationException("type", e); AssertEquals("TypeInitializationException (7)", "type", e.TypeName); AssertNotNull("TypeInitializationException (8)", e.Message); ExceptionTester.CheckHResult ("TypeInitializationException (9)", e, unchecked ((int)0x80131534)); }
private static void ThrowTypeInitializationException(TypeInitializationException ex) { // The fact that we're using static constructors to initialize this is an internal detail. // Rethrow the inner exception if there is one. // Do it carefully so as to not stomp on the original callstack. ExceptionDispatchInfo.Capture(ex.InnerException ?? ex).Throw(); throw new InvalidOperationException("Unreachable"); // keep the compiler happy }
public static Exception Unwrap(this Exception exception) { return(exception switch { TypeInitializationException typeInitializationException => typeInitializationException.InnerException.Unwrap(), TargetInvocationException targetInvocationException => targetInvocationException.InnerException.Unwrap(), AggregateException aggregateException => aggregateException.Flatten(), _ => exception });
public static Exception CreateDetailedException(this TypeInitializationException exception) { if (exception.InnerException is ReflectionTypeLoadException inner) { return(inner.CreateDetailedException()); } return(exception); }
/// <summary> /// Returns a formatted message fit for a type init exception. /// </summary> /// <param name="typeInitExc"></param> /// <returns></returns> private static LogMessage GetTypeInitThrowMessage(TypeInitializationException typeInitExc) { LogMessage message = new LogMessage(); message.AddComponent(new LogMessage.MessageComponent("[ ", RED, BLOOD_RED, false)); message.AddComponent(new LogMessage.MessageComponent(typeInitExc.GetType().FullName + " Thrown!", GOLD, null, true)); message.AddComponent(new LogMessage.MessageComponent(" ] -- ", RED, null, false)); message.AddComponent(new LogMessage.MessageComponent("Inner Exception:", ORANGE, null, true)); return(message.ConcatLocal(GetExceptionMessage(typeInitExc.InnerException))); }
static void UnwrapThrow(TypeInitializationException ex) { Exception inner = ex; while (inner.InnerException != null) { inner = inner.InnerException; } ExceptionDispatchInfo.Capture(inner).Throw(); }
public void ThrowsInvalidOperationExceptionWhenGivenGenericTypeParameterIsNotMarkedWithThePermissionAttribute() { var permissionCheckerStub = new Mock <IUserPermissionChecker>(); // Arrange && Act TypeInitializationException ex = Assert.Throws <TypeInitializationException>(() => new ServicePermissionChecker <QueryStubWithoutPermissionAttributeStub>( permissionChecker: permissionCheckerStub.Object)); // Assert Assert.That(ex.InnerException, Is.TypeOf <InvalidOperationException>()); }
public void cannot_add_new_enum_members_from_child() { TypeInitializationException catchedException = null; try { SomeEnum fourthValueAttempt = OtherChildEnum.FourthValueAttempt; } catch (TypeInitializationException e) { catchedException = e; } Assert.IsNotNull(catchedException); Assert.IsInstanceOfType(catchedException.InnerException, typeof(EnumInitializationException)); }
private int throwingMeaningfulException(Func <int> comparison) { int num; try { num = comparison(); } catch (TypeInitializationException typeInitializationException1) { TypeInitializationException typeInitializationException = typeInitializationException1; if (typeInitializationException.InnerException != null) { throw typeInitializationException.InnerException; } throw; } return(num); }
public void TypeCtor_withConcreteRole_throwsInvalidOperationException() { // arrange: TypeInitializationException exception = null; // act: try { new FakeRoleBuilder <FakeRole, FakeRole> (); } catch (TypeInitializationException ex) { exception = ex; } // assert: Assert.IsNotNull(exception); Assert.IsInstanceOf <InvalidOperationException>(exception.InnerException); }
public static unsafe void EnsureClassConstructorRun(StaticClassConstructionContext *pContext) { IntPtr pfnCctor = pContext->cctorMethodAddress; NoisyLog("EnsureClassConstructorRun, cctor={0}, thread={1}", pfnCctor, CurrentManagedThreadId); // If we were called from MRT, this check is redundant but harmless. This is in case someone within classlib // (cough, Reflection) needs to call this explicitly. if (pContext->initialized == 1) { NoisyLog("Cctor already run, cctor={0}, thread={1}", pfnCctor, CurrentManagedThreadId); return; } CctorHandle cctor = Cctor.GetCctor(pContext); Cctor[] cctors = cctor.Array; int cctorIndex = cctor.Index; try { Lock cctorLock = cctors[cctorIndex].Lock; if (DeadlockAwareAcquire(cctor, pfnCctor)) { int currentManagedThreadId = CurrentManagedThreadId; try { NoisyLog("Acquired cctor lock, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId); cctors[cctorIndex].HoldingThread = currentManagedThreadId; if (pContext->initialized == 0) // Check again in case some thread raced us while we were acquiring the lock. { TypeInitializationException priorException = cctors[cctorIndex].Exception; if (priorException != null) { throw priorException; } try { NoisyLog("Calling cctor, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId); ((delegate * < void >)pfnCctor)(); // Insert a memory barrier here to order any writes executed as part of static class // construction above with respect to the initialized flag update we're about to make // below. This is important since the fast path for checking the cctor uses a normal read // and doesn't come here so without the barrier it could observe initialized == 1 but // still see uninitialized static fields on the class. Interlocked.MemoryBarrier(); NoisyLog("Set type inited, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId); pContext->initialized = 1; } catch (Exception e) { TypeInitializationException wrappedException = new TypeInitializationException(null, SR.TypeInitialization_Type_NoTypeAvailable, e); cctors[cctorIndex].Exception = wrappedException; throw wrappedException; } } } finally { cctors[cctorIndex].HoldingThread = ManagedThreadIdNone; NoisyLog("Releasing cctor lock, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId); cctorLock.Release(); } } else { // Cctor cycle resulted in a deadlock. We will break the guarantee and return without running the // .cctor. } } finally { Cctor.Release(cctor); } NoisyLog("EnsureClassConstructorRun complete, cctor={0}, thread={1}", pfnCctor, CurrentManagedThreadId); }
public static string Error(this TypeInitializationException ex, MethodBase mb = null) { return(Error((Exception)ex, mb)); }
public void GetUninitializedObject_StaticConstructorThrows_ThrowsTypeInitializationException() { TypeInitializationException ex = Assert.Throws <TypeInitializationException>(() => FormatterServices.GetUninitializedObject(typeof(StaticConstructorThrows))); Assert.IsType <DivideByZeroException>(ex.InnerException); }
public XDocument CreateExceptionXml(Exception ex) { //load exceptions templates XDocument exceptionsTemplates; Assembly kernelAssembly = Assembly.GetAssembly(typeof(Kernel.Exceptions.ClientException)); StreamReader exReader = new StreamReader(kernelAssembly.GetManifestResourceStream("Makolab.Fractus.Kernel.Templates.Exceptions.xml")); exceptionsTemplates = XDocument.Parse(exReader.ReadToEnd()); exReader.Dispose(); // ClientException cex = ex as ClientException; XDocument exceptionXml = XDocument.Parse("<exception/>"); SqlException sqlEx = ex as SqlException; RawClientException rcex = ex as RawClientException; TypeInitializationException tiex = ex as TypeInitializationException; //Rzucenie wyjątkiem w konstruktorze wywoła wyjątek TypeInitializationException //Jeśli jest wywołany obsłużonym wyjątkiem to taki zostanie przetworzony if (tiex != null && tiex.InnerException != null) { ClientException innercex = tiex.InnerException as ClientException; if (innercex != null) { cex = innercex; } } if (sqlEx != null && sqlEx.Number == -2) { cex = new ClientException(ClientExceptionId.SqlTimeout); } if (cex != null) { var exNode = from node in exceptionsTemplates.Root.Elements() where node.Attribute("id").Value == cex.Id.ToString() select node; //copy exception template nodes to the final exception xml foreach (XElement element in exNode.ElementAt(0).Elements()) { exceptionXml.Root.Add(element); } foreach (XAttribute attribute in exNode.ElementAt(0).Attributes()) { exceptionXml.Root.Add(attribute); } // //inject parameters into exception xml if (cex.Parameters != null) { foreach (string parameter in cex.Parameters) { //dont use split because parameter value can include ':' int delimiterIndex = parameter.IndexOf(':'); string key = parameter.Substring(0, delimiterIndex); string value = parameter.Substring(delimiterIndex + 1, parameter.Length - delimiterIndex - 1); foreach (XElement element in exceptionXml.Root.Descendants()) { if (!element.HasElements) { element.Value = element.Value.Replace("%" + key + "%", value); } } } } if (cex.XmlData != null) { exceptionXml.Root.Add(cex.XmlData); } if (ConfigurationMapper.Instance.LogHandledExceptions) { ServiceHelper.Instance.LogException(ex); } else if (cex.InnerException != null) { ServiceHelper.Instance.LogException(cex.InnerException); } } else if (rcex != null) { exceptionXml.Root.Add(new XElement("customMessage", rcex.Message)); if (ConfigurationMapper.Instance.LogHandledExceptions) { ServiceHelper.Instance.LogException(ex); } } else { //if its an unhandled exception var exNode = from node in exceptionsTemplates.Root.Elements() where node.Attribute("id").Value == "UNHANDLED_EXCEPTION" select node; //copy exception template nodes to the final exception xml foreach (XElement element in exNode.ElementAt(0).Elements()) { exceptionXml.Root.Add(element); } foreach (XAttribute attribute in exNode.ElementAt(0).Attributes()) { exceptionXml.Root.Add(attribute); } // exceptionXml.Root.Element("message").Value = ex.Message; exceptionXml.Root.Element("className").Value = ex.GetType().ToString(); exceptionXml.Root.Element("serverVersion").Value = ServiceHelper.Instance.GetVersion(); //if (ex.InnerException != null) //{ // exceptionXml.Root.Add(ServiceHelper.Instance.CreateInnerExceptionXml(ex.InnerException)); //} int logNumber = ServiceHelper.Instance.LogException(ex); if (logNumber > 0) { exceptionXml.Root.Element("logNumber").Value = logNumber.ToString(CultureInfo.InvariantCulture); } else { exceptionXml.Root.Element("logNumber").Remove(); } } //leave only one language string userLang = null; if (SessionManager.SessionId != null) { try { userLang = SessionManager.Language; } catch (Exception) { RoboFramework.Tools.RandomLogHelper.GetLog().Debug("EXCEPTION: (KernelServices) What is this exception?"); } } if (userLang == null) { userLang = this.GetClientLanguageVersion(); } var localizableNodes = from node in exceptionXml.Root.Elements() where node.Attribute("lang") != null group node by node.Name.LocalName into g select g; foreach (var nodesGroup in localizableNodes) { var preferredLang = from node in nodesGroup where node.Attribute("lang").Value == userLang select node; XElement preferredElement = null; if (preferredLang.Count() > 0) { preferredElement = preferredLang.ElementAt(0); } else //select the first one { preferredElement = nodesGroup.ElementAt(0); } //delete the others foreach (XElement element in nodesGroup) { if (element != preferredElement) { element.Remove(); } } } return(exceptionXml); }
public override void Invoke(AMFContext context) { for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); if (!amfBody.IsEmptyTarget) { if (amfBody.IsWebService) { try { Type type = GetTypeForWebService(amfBody.TypeName); if (type != null) { //We can handle it with a LibraryAdapter now amfBody.Target = type.FullName + "." + amfBody.Method; } else { Exception exception = new TypeInitializationException(amfBody.TypeName, null); if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.Type_InitError, amfBody.Target), exception); } ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, exception); context.MessageOutput.AddBody(errorResponseBody); } } catch (Exception exception) { if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.Wsdl_ProxyGen, amfBody.Target), exception); } ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, exception); context.MessageOutput.AddBody(errorResponseBody); } } } else { //Flex message object content = amfBody.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; if (message != null && message is RemotingMessage) { RemotingMessage remotingMessage = message as RemotingMessage; //Only RemotingMessages for now string source = remotingMessage.source; if (source != null && source.ToLower().EndsWith(".asmx")) { try { Type type = GetTypeForWebService(source); if (type != null) { //We can handle it with a LibraryAdapter now remotingMessage.source = type.FullName; } else { Exception exception = new TypeInitializationException(source, null); if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.Type_InitError, source), exception); } ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, message, exception); context.MessageOutput.AddBody(errorResponseBody); } } catch (Exception exception) { if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.Wsdl_ProxyGen, source), exception); } ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, message, exception); context.MessageOutput.AddBody(errorResponseBody); } } } } } }
// public void Clear(List<int> l) // { // l.Clear(); // } // public void TwoCalls(List<int> l) // { // l.RemoveAt(0); // l.RemoveAt(1); // } public string CrossCalls(TypeInitializationException e) { return(e.GetType().ToString() + e.HelpLink); }
// Test the TypeInitializationException class. public void TestTypeInitializationException() { TypeInitializationException e; e = new TypeInitializationException(null, null); AssertEquals("TypeInitializationException (1)", String.Empty, e.TypeName); AssertNotNull("TypeInitializationException (2)", e.Message); ExceptionTester.CheckHResult ("TypeInitializationException (3)", e, unchecked((int)0x80131534)); e = new TypeInitializationException("type", null); AssertEquals("TypeInitializationException (4)", "type", e.TypeName); AssertNotNull("TypeInitializationException (5)", e.Message); ExceptionTester.CheckHResult ("TypeInitializationException (6)", e, unchecked((int)0x80131534)); e = new TypeInitializationException("type", e); AssertEquals("TypeInitializationException (7)", "type", e.TypeName); AssertNotNull("TypeInitializationException (8)", e.Message); ExceptionTester.CheckHResult ("TypeInitializationException (9)", e, unchecked((int)0x80131534)); }
private static void HandleInnerException(ref RunningResults results, TypeInitializationException ex) { results.Verdict = Verdict.SecurityException; results.Error = ex.ToString(); }
public override void Invoke(AMFContext context) { for (int i = 0; i < context.AMFMessage.BodyCount; i++) { Type typeForWebService; Exception exception; ErrorResponseBody body2; AMFBody bodyAt = context.AMFMessage.GetBodyAt(i); if (!bodyAt.IsEmptyTarget) { if (bodyAt.IsWebService) { try { typeForWebService = this.GetTypeForWebService(bodyAt.TypeName); if (typeForWebService != null) { bodyAt.Target = typeForWebService.FullName + "." + bodyAt.Method; } else { exception = new TypeInitializationException(bodyAt.TypeName, null); if ((log != null) && log.get_IsErrorEnabled()) { log.Error(__Res.GetString("Type_InitError", new object[] { bodyAt.Target }), exception); } body2 = new ErrorResponseBody(bodyAt, exception); context.MessageOutput.AddBody(body2); } } catch (Exception exception1) { exception = exception1; if ((log != null) && log.get_IsErrorEnabled()) { log.Error(__Res.GetString("Wsdl_ProxyGen", new object[] { bodyAt.Target }), exception); } body2 = new ErrorResponseBody(bodyAt, exception); context.MessageOutput.AddBody(body2); } } } else { object content = bodyAt.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; if ((message != null) && (message is RemotingMessage)) { RemotingMessage message2 = message as RemotingMessage; string source = message2.source; if ((source != null) && source.ToLower().EndsWith(".asmx")) { try { typeForWebService = this.GetTypeForWebService(source); if (typeForWebService != null) { message2.source = typeForWebService.FullName; } else { exception = new TypeInitializationException(source, null); if ((log != null) && log.get_IsErrorEnabled()) { log.Error(__Res.GetString("Type_InitError", new object[] { source }), exception); } body2 = new ErrorResponseBody(bodyAt, message, exception); context.MessageOutput.AddBody(body2); } } catch (Exception exception2) { exception = exception2; if ((log != null) && log.get_IsErrorEnabled()) { log.Error(__Res.GetString("Wsdl_ProxyGen", new object[] { source }), exception); } body2 = new ErrorResponseBody(bodyAt, message, exception); context.MessageOutput.AddBody(body2); } } } } } }
public string Type(TypeInitializationException e) { return(e.TypeName); }
public string TwoCalls(TypeInitializationException e) { return(e.TypeName + e.TypeName); }
public string Help(TypeInitializationException e) { return(e.Message); }
private static RunningResults HandleInnerException(TypeInitializationException ex) { return(new RunningResults(Verdict.SecurityException, output: ex.ToString())); }
private static IBssomFormatter <T> Throw <T>(TypeInitializationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException ?? ex).Throw(); return(default);