Exception thrown inside Exceptional logging - c#

I’m replacing Elmah with Exceptional, but having an issue. It works fine if the exception is thrown inside my web project or if the error is a 404 (The controller for path '/blah/blah' was not found or does not implement IController).
But if I throw an exception from within one of my referenced projects that’s not my web project, then Exceptional throws an error when attempting to log. The following error and stacktrace only gets displayed in the console. The error gets swallowed at that point and doesn't get logged anywhere.
One of the beauties of open-source, is that I can see the code that’s throwing the exception, but no idea why…
Error.cs (line 107, 135, 126)
Exception thrown: 'System.ArgumentException' in Cms.Services.dll
'w3wp.exe' (CLR v4.0.30319: /LM/W3SVC/1/ROOT/wssp-18-131152201224510365): Loaded 'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.HttpRequest.CalcDynamicServerVariable(DynamicServerVariable var)
at System.Web.HttpServerVarsCollectionEntry.GetValue(HttpRequest request)
at System.Web.HttpServerVarsCollection.GetServerVar(Object e)
at System.Web.HttpServerVarsCollection.Get(Int32 index)
at System.Web.HttpServerVarsCollection.GetValues(Int32 index)
at System.Collections.Specialized.NameValueCollection.Add(NameValueCollection c)
at StackExchange.Exceptional.Error.<>c__DisplayClass22_0.<SetContextProperties>b__0(Func`2 getter) in C:\BuildAgent\work\d20fce4a5bb47bd3\StackExchange.Exceptional\Error.cs:line 126
at StackExchange.Exceptional.Error.SetContextProperties(HttpContext context) in C:\BuildAgent\work\d20fce4a5bb47bd3\StackExchange.Exceptional\Error.cs:line 135
at StackExchange.Exceptional.Error..ctor(Exception e, HttpContext context, String applicationName) in C:\BuildAgent\work\d20fce4a5bb47bd3\StackExchange.Exceptional\Error.cs:line 107
at StackExchange.Exceptional.ErrorStore.LogException(Exception ex, HttpContext context, Boolean appendFullStackTrace, Boolean rollupPerServer, Dictionary`2 customData, String applicationName) in C:\BuildAgent\work\d20fce4a5bb47bd3\StackExchange.Exceptional\ErrorStore.cs:line 611
I am registering Exceptional like this:
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyApp"].ConnectionString;
ErrorStore.Setup("MyApp", new SQLErrorStore(connectionString));
And this is the only code in my web.config:
<modules runAllManagedModulesForAllRequests="true">
<add name="ErrorStore" type="StackExchange.Exceptional.ExceptionalModule, StackExchange.Exceptional" />
</modules>

I finally found the issue. The code below is what I use to logout a user from my application.
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.SignOut();
authenticationManager.User = new ClaimsPrincipal();
When the 3rd line executes and sets the user to a new ClaimsPrinciple, it removes the following 3 values (AUTH_TYPE, AUTH_USER, REMOTE_USER) and sets them to null inside the System.Web.HttpContext.Current.Request.ServerVariables object, even though the keys are still there inside the object.
So any exception thrown after that line is not logged by Stackexchange.Exceptional, as it tries to read those values and then throws a System.NullReferenceException.

Related

FluentNHibernate.Cfg.FluentConfigurationException

Just some background: it was working code in Production since 2013. Recently added DB password encrypt/decrypt logic in code - compiled code using VS2010 - it's working fine in test but not in Production.
I am assuming it has something to do with configuration xml , mapping or some mismatch of NHibernate dll. Not sure if build/output folders need some thing?
Error in Production:
FluentNHibernate.Cfg.FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
NHibernate MappingException: Could not compile the mapping document: (XmlDocument) ---> System.InvalidCastException: [A]NHibernate.Cfg.MappingSchema.HbmMapping cannot be cast to [B]NHibernate.Cfg.MappingSchema.HbmMapping. Type A originates from 'NHibernate, Version=2.1.2.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4' in the context 'Default' at location 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\drcwm\bb04bdb4\da32eda4\assembly\dl3\bb71f3c5\00f7c13c_ef33d101\NHibernate.dll'. Type B originates from 'NHibernate, Version=2.1.2.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4' in the context 'LoadFrom' at location 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\drcwm\bb04bdb4\da32eda4\assembly\dl3\44ab434f\00f7c13c_ef33d101\NHibernate.dll'.
at NHibernate.Cfg.XmlHbmBinding.Binder.Deserialize[T](XmlNode node)
at NHibernate.Cfg.XmlHbmBinding.MappingRootBinder.Bind(XmlNode node)
at NHibernate.Cfg.Configuration.AddValidatedDocument(NamedXmlDocument doc)
--- End of inner exception stack trace ---
at NHibernate.Cfg.Configuration.AddValidatedDocument(NamedXmlDocument doc)
at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
at NHibernate.Cfg.Configuration.AddDocument(XmlDocument doc, String name)
at FluentNHibernate.PersistenceModel.Configure(Configuration cfg)
at FluentNHibernate.Cfg.FluentMappingsContainer.Apply(Configuration cfg)
at FluentNHibernate.Cfg.MappingConfiguration.Apply(Configuration cfg)
at FluentNHibernate.Cfg.FluentConfiguration.BuildConfiguration()
--- End of inner exception stack trace ---
at FluentNHibernate.Cfg.FluentConfiguration.BuildConfiguration()
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory()
--- End of inner exception stack trace ---
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory()
at DB.FIOS_SOUTH.DataBase.get_SessionFactory()
NLog.LoggerImpl.Write Error "System.NullReferenceException: Object reference not set to an instance of an object.
at DB.Base.DataBase.get_Session()
at DB.Base.DataBase.Query[T]()
at RemoteService.BaseListService.FilteredQuery[T](BaseParameter parameter, DataBase db, Boolean applyPagination, Boolean applySortOrder)
at RemoteService.JobsListService.GetJobsWithChildrenCount[T](JobParameter parameter)
Code throwing exception is below:
if (_ISessionFactory == null)
{
try
{
_ISessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005
.ConnectionString(ConnectionString).IsolationLevel(IsolationLevel.ReadUncommitted)
.Cache(c => c.ProviderClass<HashtableCacheProvider>())
)
.Mappings(m =>
{
m.HbmMappings
.AddFromAssemblyOf<FIOS_NORTH_QUEUES.DataBase>();
m.FluentMappings
.AddFromNamespaceOf<FIOS_NORTH_QUEUES.Map.QueueWFADOItemMap>();
})
.ExposeConfiguration(ModifyConfiguration)
.BuildSessionFactory();
}
catch (Exception ex)
{
logger.Error(ex);
}
}
your production process has already loaded NHibernate from an old (shadow-)cache location then the new dlls are loaded from a new location and try to load their dependencies next to them, but since the process already loaded the assemblies from elsewhere it has a conflict.
You have to try unloading/restarting the AppDomain by restarting the server process, asp.net process, iis, whatever. The error is not related to the code at all.

"Attempted to access an element as a type incompatible with the array" thrown during creating a custom EmailService in Postal

I'm trying to configure Postal in class library project. To do this I need to configure custom EmailService. On Postal webpage there's a snippet for doing this:
// Get the path to the directory containing views
var viewsPath = Path.GetFullPath(#"..\..\Views");
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));
var service = new EmailService(engines);
(See here: http://aboutcode.net/postal/outside-aspnet.html)
Surprisingly, following error is thrown:
System.ArrayTypeMismatchException occurred HResult=-2146233085
Message=Attempted to access an element as a type incompatible with the
array. Source=mscorlib StackTrace:
at System.Collections.Generic.List`1.Insert(Int32 index, T item) InnerException:
To be precise - it's thrown during adding FileSystemRazorViewEngine to ViewEngineCollection. FileSystemRazorViewEngine derives from IViewEngine and ViewEngineCollection derives from Collection<IViewEngine>.
And here's stacktrace:
mscorlib.dll!System.Collections.Generic.List.Insert(int
index, System.__Canon item) + 0x3e bytes
System.Web.Mvc.dll!System.Web.Mvc.ViewEngineCollection.InsertItem(int
index, System.Web.Mvc.IViewEngine item) + 0x89 bytes
I can't figure out what causes the exception.
I am getting same error. I suspect that Postal is built with slightly different version of System.Web.Mvc that the main project that causing ViewEngine incompatibility... But I only have production binaries of the postal...

ILNumerics.Misc.ILThreadPool' threw an exception when ILNumerics.Settings.UseThreadAffinity is not manually set to false

Sometimes when I use ILMath functions such as ILMath.linspace and others, the following exception is thrown without obvious reason.
System.TypeInitializationException was unhandled by user code
HResult=-2146233036
Message=The type initializer for 'ILNumerics.Misc.ILThreadPool' threw an exception.
Source=ILNumerics
TypeName=ILNumerics.Misc.ILThreadPool
StackTrace:
at ILNumerics.Misc.ILThreadPool.Wait4Workers(Int32& workerCount)
at ILNumerics.ILMath.multiplyElem(ILInArray`1 A, ILInArray`1 B)
at ILNumerics.ILDenseArray`1.op_Multiply(ILDenseArray`1 A, ILDenseArray`1 B)
at ILNumerics.ILMath.linspace[T](ILBaseArray start, ILBaseArray end, ILBaseArray length)
at ILNumerics.ILMath.linspace(ILBaseArray start, ILBaseArray end, ILBaseArray length)
at *** in ***\Numerics\NumericsTest.cs:line 104
at *** in ***\Numerics\NumericsTest.cs:line 94
InnerException: System.ComponentModel.Win32Exception
HResult=-2147467259
Message=The parameter is incorrect
Source=System
ErrorCode=-2147467259
NativeErrorCode=87
StackTrace:
at System.Diagnostics.ProcessThread.set_ProcessorAffinity(IntPtr value)
at ILNumerics.Misc.ILThreadPool..ctor(Int32 maxThreads)
at ILNumerics.Misc.ILThreadPool..cctor()
InnerException:
By trial and error, I realized that if I set ILNumerics.Settings.UseThreadAffinity = false,
The code then executes without error. I read from ILNumerics documentation that UseThreadAffinity should default to false, which in my case it is definitely set to true by default. Is this a bug? Another problem I notice that the documentation also mentions I can use App.config to change default settings, I tried that and the ILNIsHosted actually does what it says, but ILNUseThreadAffinity has no effect at all on the UseThreadAffinity setting. It is still “true” even though I tried set it to false. Is this a bug of ILNumerics? I’m using ILNumerics 3.2.2.0 (any CPU)obtained from NuGet directly. The code is running in VS2010 on Windows 7 64bit.
<appSettings>
<add key="ILNIsHosted" value="true" />
<add key="ILNUseThreadAffinity" value="false"/>
</appSettings>
To add on to the original question, I went to download the source code of ILNumerics community edition and discovered something strange.
ILSettings.cs contains the following:
public static bool UseThreadAffinity {
get { return s_isHosted; }
set { s_isHosted = value; }
}
These lines don't make sense to me. Why is UseThreadAffinity set to s_isHosted. I think this may be why when I set ILNIsHosted to true, the thread affinity changed to true as well.

MEF Composition error not propagating inner exception (except through message)

I am working with MEF to load modules from different sources into my app. I have an example (code below) where I create a class that is composable which throws an exception in the constructor. That exception causes the composition to fail and thus throw an exception that says "why"... In the statement it says that the cause is an InvalidCastException... which is true.
If I print the exception, I know why it fails, but how do I retrieve the ACTUAL original exception (InvalidCastException) thrown, in order for me to handle it properly -- rather than just a generic catch, which would miss other exceptions -- in the module that is asking for an instance of the said class? Querying the CompositionException.Errors doesn't give me the original exception either...
CODE:
using System.ComponentModel.Composition;
using Microsoft.Practices.ServiceLocation;
[Export(typeof(A))]
Class A
{
[ImportingConstructor]
public A(ISomeinterface x, ISomeOtherInterface y)
{
//// Throw some exception (in my code it happens to be an InvalidCastException)
throw new InvalidCastException ("Unable to cast object of type 'Sometype' to type 'Someothertype'.");
}
}
Class B
{
public B(IServiceLocator serviceLocator)
{
try
{
//// Here is where the exception would be thrown as an "ActivationException"
A myAInstance = serviceLocator.GetInstance(A);
}
catch (ActivationException activationException)
{
//// Print original activation exception from trying to get the service
System.Diagnostics.Debug.WriteLine(activationException);
if (ex.InnerException is CompositionException)
{
CompositionException compositionException = (CompositionException)activationException.InnerException;
//// *** Here is where I want to retrieve the InvalidCastException in order to handle it properly
//// *** Also, componentException.InnerException is "null" and so is the componentException.Errors[0].Exception.InnerException
}
else
{
throw;
}
}
}
}
OUTPUT:
Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type A, key "" ---> System.ComponentModel.Composition.CompositionException: The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) Unable to cast object of type 'Sometype' to type 'Someothertype'.
Resulting in: An exception occurred while trying to create an instance of type 'A'.
Resulting in: Cannot activate part 'A'.
Element: A --> A --> DirectoryCatalog (Path="C:\path\to\code\")
Resulting in: Cannot get export 'A (ContractName="A")' from part 'A'.
Element: A (ContractName="A") --> A --> DirectoryCatalog (Path="C:\path\to\code\")
at System.ComponentModel.Composition.Hosting.CompositionServices.GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition)
at System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportedValue(CatalogPart part, ExportDefinition export, Boolean isSharedPart)
at System.ComponentModel.Composition.ExportServices.GetCastedExportedValue[T](Export export)
at System.ComponentModel.Composition.ExportServices.<>c__DisplayClass10`2.<CreateSemiStronglyTypedLazy>b__d()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at Microsoft.Practices.Prism.MefExtensions.MefServiceLocatorAdapter.DoGetInstance(Type serviceType, String key) in c:\release\WorkingDir\PrismLibraryBuild\PrismLibrary\Desktop\Prism.MefExtensions\MefServiceLocatorAdapter.cs:line 73
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
--- End of inner exception stack trace ---
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance[TService]()
at <code> line whatever...
System.ComponentModel.Composition.CompositionException: The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
I found the solution the actual exception is nested deep in the compositionException.Errors hierarchy. One would think the original exception would be under the original composition exception but actually this is how to access it:
It happens to be the innerexception inside one of the errors of another composition exception which is itself one of the errors in the original composition exception
CompositionException compositionException = (CompositionException)activationException.InnerException;
CompositionException innerCompositionException = compositionException.Errors[0].Exception;
InvalidCastException castException = (InvalidCastException)innerCompositionException.Errors[0].Exception.InnerException
I won't delete this in case someone else runs into the same thing.

IntellitraceFile throwing strange error

Can someone explain this error? (it showed up after enabling tracing in the collection plan.)
Test method ExecuteTaskTest threw exception:
System.ArgumentException: An item with the same key has already been added.
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
Microsoft.VisualStudio.IntelliTrace.IntelliTraceProcess.AddModule(IntelliTraceModule module)
Microsoft.VisualStudio.IntelliTrace.IntelliTraceProcess.Initialize(IntelliTraceFile traceDebugLogFile)
Microsoft.VisualStudio.IntelliTrace.IntelliTraceProcess..ctor(IntelliTraceFile traceDebugLogFile)
**Microsoft.VisualStudio.IntelliTrace.IntelliTraceFile.get_Processes()**
Microsoft.VisualStudio.Samples.IntelliTraceReader..ctor(String logFileName) in C:\workspace\agileproductlinerdsl\ITraceLogParser\IntelliTraceReader.cs: line 49
UofCASE.AgileProductLinerDSL.Nant.AspenTest.writeTraceResult(FileInfo itraceLog, FileInfo resultFile) in C:\workspace\agileproductlinerdsl\NantTask\AspenTest.cs: line 148
UofCASE.AgileProductLinerDSL.Nant.AspenTest.runTests(FeatureTestMap tests) in C:\workspace\agileproductlinerdsl\NantTask\AspenTest.cs: line 124
UofCASE.AgileProductLinerDSL.Nant.AspenTest.ExecuteTask() in C:\workspace\agileproductlinerdsl\NantTask\AspenTest.cs: line 56
APLDTests.AspenTestTest.ExecuteTaskTest() in C:\workspace\agileproductlinerdsl\APLDTests\AspenTestTest.cs: line 37
It's a known issue with IntelliTrace. The log file was likely collected from an app that had the same module loaded into multiple app domains and this causes IntelliTrace to barf when grabbing the Process list as you can see.

Categories

Resources