FluentNHibernate.Cfg.FluentConfigurationException - c#

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.

Related

Exception thrown inside Exceptional logging

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.

Specified cast is not valid. error shows in window server 2008 r2

I made a application in asp.net c# using linq and oracle database.This application is working fine on Widows 7 32 bit local host.But When I deployed this application in windows server 2008 r2.It gives a following error.Guide me what is the following error.How Can I check this error on deployment server and How can I resolved this error
Specified cast is not valid. Description: An unhandled exception
occurred during the execution of the current web request. Please
review the stack trace for more information about the error and where
it originated in the code.
Exception Details: System.InvalidCastException: Specified cast is not
valid.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidCastException: Specified cast is not valid.]
System.Data.UnboxT`1.ValueField(Object value) +54
sis.<>c__DisplayClass55.b__0(DataRow r) +38
System.Linq.WhereEnumerableIterator`1.MoveNext() +156
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +165
System.Linq.d__81`1.MoveNext() +472
System.Linq.Enumerable.Count(IEnumerable`1 source) +267
sis.regreport.Page_Load(Object sender, EventArgs e) +5015
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +3178
var vcolM = dt.AsEnumerable()
.Where(r => r.Field<string>("MAJ") == (string)vprglist
&& r.Field<string>("SPEC") == (string)vspecourse
&& r.Field<string>("L_ABR_CODE") == (string)genderEng[1]
&& r.Field<string>("reg") == (string)drRegion["reg"]
&& r.Field<decimal>("year") == syrcnt)
.Sum(r => Convert.ToInt32(r["strength"]));
All linq like above working fine in local pc.But giving error in windows server 2008.Where syrcnt is int.
The most likely cause of the InvalidCastException is the r.Field<string>("MAJ") , r.Field<decimal>("year") line. The Field<T> extension method will throw an InvalidCastException in the case where the actual type of the data doesn't match the type which was passed to Field<T>.
OR
lies in here Convert.ToInt32(r["strength"]), the strength might not be getting proper type
Honestly, I think you issues lies in the line r.Field<decimal>("year"). I may be wrong as there is not much information about the datatype of your variable syrcnt
Hence giving you the exception System.InvalidCastException: Specified cast is not valid

VirtualPathProvider issue

Implemented a virtual path provider to dynamically load some files from a shared project in a new web application. Everything works fine in dev/deployed and local IIS. When deploying to production we are encountering "Failed to start monitoring file changes" error when trying to find a 'virtual file'. GetCacheDependency is overridden in our VirtualPathProvider but when I remote debug the function is never hit. Any Ideas?
EDIT:
public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
{
if (CheckVirtual(virtualPath))
{
string realName = CustomVirtualPathProvider.CleansePath(virtualPath);
return new System.Web.Caching.CacheDependency(baseDirectory + realName);
}
return Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
}
I register the VPP in the global asax. It only fails in production which leads me to believe that its a iis settings issue.
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:

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.

Strange COM interop exception 0x80005000 using System.DirectoryServices.AccountManagement libraries

I'm trying to write something that (amongst other things) adds a user to an AD group - using VS2010, .Net4 and the library facilities in System.DirectoryServices.AccountManagement.
I've gotten a user and group by code like the sample below, and this works for other operations like enabling or disabling accounts.
group = System.DirectoryServices.AccountManagement.GroupPrincipal.FindByIdentity(_UserContext, Name);
user = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(_UserContext, Name);
Now, trying to add the user to the group like:
group.Members.Add(user);
I get an error with a stack trace beginning like the one listed below with a COM interop error 0x80005000 (unknown). This also happens with other users and on 32 and 64 bit builds. Searching this on the web comes up with a few forum questions, but I can't find any answers. In theory, this should work - this codeproject sample is doing much the same thing.
Has anyone seen this error or have any idea what might have caused it?
Stack trace top:
Unhandled Exception: System.DirectoryServices.AccountManagement.PrincipalOperati
onException: Unknown error (0x80005000) ---> System.Runtime.InteropServices.COME
xception: Unknown error (0x80005000)
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne
)
at System.DirectoryServices.DirectorySearcher.FindOne()
at System.DirectoryServices.AccountManagement.ADStoreCtx.IsMemberOfInStore(Gr
oupPrincipal g, Principal p)
--- End of inner exception stack trace ---
at System.DirectoryServices.AccountManagement.ADStoreCtx.IsMemberOfInStore(Gr
oupPrincipal g, Principal p)
at System.DirectoryServices.AccountManagement.PrincipalCollection.ContainsNat
iveTest(Principal principal)
at System.DirectoryServices.AccountManagement.PrincipalCollection.Contains(Pr
incipal principal)
at System.DirectoryServices.AccountManagement.PrincipalCollection.Add(Princip
al principal)
at System.DirectoryServices.AccountManagement.PrincipalCollection.Add(UserPri
ncipal user)
I also ran into the same issue with a (GroupPrincipal instance).Members.Add(UserPrincipal instance).
The workaround (in IronPython) is rather simple thanks to the GetUnderlyingObject method.
de = group.GetUnderlyingObject
# Group member DNs are kept in 'member' attribute in LDAP
de.Properties['member'].Add(user.DistinguishedName)
de.CommitChanges() # Save your work
Just ran into this and noticed that the code project sample was explicitly using the domain's name when creating the context (instead of using null). I changed my code to explicitly specify the domain name, and now it's working fine - I can group.Members.Add(user) without issue.

Categories

Resources