NHibernate: Collection was modified; enumeration operation may not execute - nhibernate

I'm currently struggling with this "Collection was modified; enumeration operation may not execute" issue.
I have searched about this error message, and it's all related to the foreach statement. I do have the some foreach statements, but they are just simply representing the data. I did not using any remove or add inside the foreach statement.
NOTE:
The error randomly happens (about 4-5 times a day).
The application is the MVC website.
There are about 5 users operate this applications (about 150 orders a day). Could it be some another users modified the collection, and then occur this error?
I have log4net setup and the settings can be found here
Make sure that the controller has a parameterless public constructor I do have parameterless public constructor in AdminProductController
Does anyone know why this happen and how to resolve this issue?
A friend (Oskar) mentioned that
"Theory: Maybe the problem is that
your configuration and session factory
is initialized on the first request
after application restart. If a second
request comes in before the first
request is finished, maybe it will
also try to initialize and then
triggering this problem somehow."
Many thanks.
Daoming
Here is the error message:
System.InvalidOperationException
Collection was modified; enumeration operation may not execute.
System.InvalidOperationException: An error occurred when trying to create a controller of type 'WebController.Controllers.Admin.AdminProductController'. Make sure that the controller has a parameterless public constructor. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> NHibernate.MappingException: Could not configure datastore from input stream DomainModel.Entities.Mappings.OrderProductVariant.hbm.xml ---> System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext()
at System.Xml.Schema.XmlSchemaSet.AddSchemaToSet(XmlSchema schema)
at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlSchema schema)
at System.Xml.Schema.XmlSchemaSet.Add(XmlSchema schema)
at NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
--- End of inner exception stack trace ---
at NHibernate.Cfg.Configuration.LogAndThrow(Exception exception)
at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
at NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly)
at NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly)
at DomainModel.RepositoryBase..ctor()
at WebController.Controllers._baseController..ctor()
at WebController.Controllers.Admin.AdminProductController..ctor()
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
--- End of inner exception stack trace ---
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
--- End of inner exception stack trace ---
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Oskar is right. Two separate threads are trying to initialize the session factory at the same time. Suggest you put some locking around the initialization code, perhaps just using the lock keyword and a suitable synchronization object. We've used a pattern like this, using one of the locks from the Wintellect PowerThreading library:
using (_lock.WaitToRead())
{
if (Factory != null) return Factory;
}
using (_lock.WaitToWrite())
{
if (Factory != null) return Factory;
Factory = ConfigureFactory();
return Factory;
}
You could more simply just use the lock keyword and a double-check locking pattern like so:
class NestedSessionManager
{
internal static SessionManager _sessionManager;
private static readonly object _syncRoot = new object();
internal static SessionManager sessionManager
{
get
{
if (_sessionManager != null) return _sessionManager;
lock (_syncRoot)
{
if (_sessionManager != null) return _sessionManager;
_sessionManager = new SessionManager();
return _sessionManager;
}
}
}
}

Related

Simple Injector instance is requested outside the context of an active (async scope) scope

I'm trying to inject my IAuthorizationRepository into my VB Web App using SimpleInjector.
Public Class IdentityPackage
Implements IPackage
Public Sub RegisterServices(container As Container) Implements IPackage.RegisterServices
container.Register(Of IUserStore(Of User, Integer), UserStore)(Lifestyle.Scoped)
container.Register(Of IAuthorizationRepository, AuthorizationRepository)(Lifestyle.Scoped)
container.Register(Of ISession, Session)()
End Sub
End Class
Here's my startup.
Public Partial Class Startup
Public Sub Configuration(app As IAppBuilder)
Dim container = ConfigureSimpleInjector(app)
Dim config = New HttpConfiguration() With {
.DependencyResolver = New SimpleInjectorWebApiDependencyResolver(container)
}
ConfigureOAuth(app, container)
WebApiConfig.Register(config)
app.UseCors(CorsOptions.AllowAll)
app.UseWebApi(config)
End Sub
End Class
And here's my ConfigureOAuth.
Public Sub ConfigureOAuth(app As IAppBuilder, container As Container)
Dim authRepositoryFactory As Func(Of IAuthorizationRepository) = container.GetInstance(Of IAuthorizationRepository)
Dim authorizationOptions = New OAuthAuthorizationServerOptions() With {
.AllowInsecureHttp = True,
.TokenEndpointPath = New PathString("/api/token"),
.AccessTokenExpireTimeSpan = TimeSpan.FromHours(4),
.Provider = New AuthorizationServerProvider(authRepositoryFactory)
}
' Token Generation
app.UseOAuthAuthorizationServer(authorizationOptions)
app.UseOAuthBearerAuthentication(New OAuthBearerAuthenticationOptions())
End Sub
When it gets to the first line under ConfigureOAuth, it throws the error The AuthorizationRepository is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.
The strange thing is that I'm converting an existing, and fully functional C# project into VB, and this is the VB equivalent of the codebase in C#, but the C# code does not have this problem. This makes me feel like the issue lies in how VB handles the code, as opposed to C#, but I don't see how that could be the case with this example. Can anyone tell me what's going wrong?
The following is my stack trace:
[ActivationException: The AuthorizationRepository is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.]
SimpleInjector.Scope.GetScopelessInstance(ScopedRegistration`1 registration) +168
SimpleInjector.Scope.GetInstance(ScopedRegistration`1 registration, Scope scope) +52
SimpleInjector.Advanced.Internal.LazyScopedRegistration`1.GetInstance(Scope scope) +158
lambda_method(Closure ) +223
SimpleInjector.InstanceProducer.BuildAndReplaceInstanceCreatorAndCreateFirstInstance() +32
SimpleInjector.InstanceProducer.GetInstance() +235
SimpleInjector.Container.GetInstanceForRootType() +154
SimpleInjector.Container.GetInstance() +146
ClientWebAppVB.Api.Startup.ConfigureOAuth(IAppBuilder app, Container container) in C:\Projects\TEST\ClientWebAppVB\ClientWebAppVB.Api\App_Start\OAuthConfig.vb:10
ClientWebAppVB.Api.Startup.Configuration(IAppBuilder app) in C:\Projects\TEST\ClientWebAppVB\ClientWebAppVB.Api\Startup.vb:15
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +160
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
Owin.Loader.<>c__DisplayClass12.<MakeDelegate>b__b(IAppBuilder builder) +66
Owin.Loader.<>c__DisplayClass1.<LoadImplementation>b__0(IAppBuilder builder) +123
Microsoft.Owin.Host.SystemWeb.<>c__DisplayClass2.<InitializeBlueprint>b__0(IAppBuilder builder) +71
Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action`1 startup) +462
Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build(Action`1 startup) +40
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +70
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +106
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +536
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +173
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +10044576
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
The strange thing is that I'm converting an existing, and fully functional C# project into VB, and this is the VB equivalent of the codebase in C#, but the C# code does not have this problem
Well this is actually not the equivalent of the c# version. And unless you changed Option Explicit and Option Strict settings I'm pretty sure the code you show does not even compile. Or in your real code you omitted the As Func(Of IAuthorizationRepository) clause.
In c# this two lines are 2 totally different things:
// create a delegate
Func<IAuthorizationRepository> authRepositoryFactory =
container.GetInstance<IAuthorizationRepository>;
// and directly call a delegate or method
Func<IAuthorizationRepository> authRepositoryFactory =
container.GetInstance<IAuthorizationRepository>();
And here the second line does not compile. This line returns IAuthorizationRepository and therefore is not assignable to Func<IAuthorizationRepository>.
In Vb.Net however the following lines are exactly the same. The braces of a method call are totally optional.
' Directly call the method
Dim authRepositoryFactory = container.GetInstance(Of IAuthorizationRepository)
' And directy call the method
Dim authRepositoryFactory = container.GetInstance(Of IAuthorizationRepository)()
If you hover over authRepositoryFactory you'll see that the inferred type is IAuthorizationRepository for both lines.
To create a delegate instead of directly invoking it in VB you need to use the AddressOf Operator
Dim authRepositoryFactory = New Func(Of IAuthorizationRepository)(
AddressOf container.GetInstance(Of IAuthorizationRepository))
'or
Dim authRepositoryFactory As Func(Of IAuthorizationRepository) =
AddressOf container.GetInstance(Of IAuthorizationRepository)
If you would hover over authRepositoryFactory you'll see this is actually a Func (Of IAuthorizationRepository)

How to call Dot NET method with parameters by MULE DotNet connector?

I am trying to call .Net method from my ESB Mule project.
I created the following class in VS 2013:
namespace NicePerform.ESBDataResolver
{
public class DataResolver
{
public Object InitInfrastructure(string sysAdminURL, string delimiter, int refreshIntervalInMin)
{
/// do something
}
}
}
In the Mule project I configured DotNet connector.
<dotnet:config name="DotNet_Connector" assemblyType="NicePerform.ESBDataResolver.DataResolver, NicePerform.ESBDataResolver" assemblyPath="D:\tfs\NGA\Splash\ESB\Debug\NicePerform.ESBDataResolver.dll" scope="Singleton" doc:name="DotNet Connector"/>
<dotnet:execute config-ref="DotNet_Connector" methodName="InitInfrastructure(System.String sysAdminURL, System.String delimiter, System.Int32 refreshIntervalInMin)" doc:name="DotNet Connector"/>
I am filling the payload:
{"sysAdminURL":"${sysAdmin}","delimiter":"${delimiter}","refreshIntervalInMin":"${userAdminRefreshInterval}"}
But on call .net method I am failing with the following exception:
System.Exception: Error looking for method named InitInfrastructure(System.String sysAdminURL, System.String delimiter, System.Int32 refreshIntervalInMin) : The method name InitInfrastructure(System.String sysAdminURL, System.String delimiter, System.Int32 refreshIntervalInMin) doesn't exist
Server stack trace:
at Org.Mule.Api.Component.ComponentLoader.MethodLookUp(Object component, String methodName, MuleMessage message)
at Org.Mule.Api.Component.ComponentLoader.ExecuteComponent(String assembly, String type, String methodName, MuleMessage message, Boolean isSingleton)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Org.Mule.Api.Component.ComponentLoader.ExecuteComponent(String assembly, String type, String methodName, MuleMessage message, Boolean isSingleton)
at Org.Mule.Api.Component.ComponentManager.Execute(String assembly, String typeName, String methodName, MuleMessage message, Boolean isSingleton)
at Org.Mule.Api.Routing.Router.Process(ProcessRequest request)
at Org.Mule.Api.Routing.__Router.Process0(IntPtr __envp, JniLocalHandle __obj, JniLocalHandle request)
I try to set namespace together with method name with no success. If I am changing calling method signature to receive single string parameter - it works. What I am doing wrong?
Everything looks correct to me, but I dont have examplecode setup for it.
You mention that you have tested with setting the namespace with the method name. have you also tested the Classname together with the method name or both?
In C# int is equal to System.Int32, and I assume this doesnt cause the issue, but it might be related.
In the example files with the connector they use a slightly different notation for the methodName field: . Since we cant find an issue in your code, you could just as well try a few other ways of calling it.

Resolution failure on app reload in MVC4 + Unity

I'm working on an ASP.NET MVC4 application, using Unity 3 as DI framework.
I designed the architecture in a modular way, creating several satellite library projects (facade, managers, DB adapters, etc.), all statically linked to the app (which means added as references to the web project).
The reason behind such architecture is to allow reusage in other contexts (for instance a separate REST based backend service, implemented as a standalone web project).
I'm using dependency injection, which occurs at web project level, but also in the satellite DLLs. In order to centralize DI resolution, I'm using a simple interface
public interface IIocInstaller
{
void Setup(IUnityContainer container);
}
and each library project has a class implementing that interface. Using reflection, the web app scans all loaded assemblies for a class implementing the interface, and calls the Setup method.
Everything works when I start the app. However, when the web app is unloaded by the web server due to inactivity, on next request the following exception is thrown:
[InvalidOperationException: The type ICustomerFacade does not have an accessible constructor.]
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForNullExistingObject(IBuilderContext context) +178
lambda_method(Closure , IBuilderContext ) +25
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +35
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +10
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +196
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +193
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +113
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +48
lambda_method(Closure , IBuilderContext ) +111
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +35
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +10
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +196
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +193
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +165
[ResolutionFailedException: Resolution of the dependency failed, type = "Eden.SMS.UI.Web.Controllers.CustomersController", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type ICustomerFacade does not have an accessible constructor.
-----------------------------------------------
At the time of the exception, the container was:
Resolving Eden.SMS.UI.Web.Controllers.CustomersController,(none)
Resolving parameter "customerFacade" of constructor Eden.SMS.UI.Web.Controllers.CustomersController(Eden.SMS.Service.Facades.Interface.ICustomerFacade customerFacade)
Resolving Eden.SMS.Service.Facades.Interface.ICustomerFacade,(none)
]
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +329
Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides) +15
Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides) +18
Unity.Mvc4.UnityDependencyResolver.GetService(Type serviceType) +67
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +41
[InvalidOperationException: An error occurred when trying to create a controller of type 'Eden.SMS.UI.Web.Controllers.CustomersController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +77
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +66
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +191
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
All unity related code is performed in Application_Start. The ICustomerFacade interface is injected in a controller, and it is subject itself to injection of other instances, of course still using DI.
The error message warns about the controller having a parameterless constructor, which is of course not implemented because I need the one with injected parameters - I've also tried to specify the constructor to be used (by using InjectionConstructor), but with no luck.
Any idea why that exception is thrown?
Update
It looks like the problem is due to failure invoking the initializer in the satellite projects.
This is the code that I'm using to scan all assemblies looking for instances implementing the IIocInstaller interface
public class AssemblyInjector
{
/// <summary>
/// Initialize IoC in all assemblies implementing the IocExportAssembly attribute
/// </summary>
/// <param name="container"></param>
/// <param name="assemblyPrefix">The prefix of the assembly names to load</param>
public static void RegisterAssemblyTypes(IUnityContainer container, string assemblyPrefix)
{
var bootstrapers = EnumerateIocBootstraperTypes(assemblyPrefix);
foreach ( Type type in bootstrapers )
{
var instance = (IIocInstaller) Activator.CreateInstance(type);
instance.Setup(container);
}
}
/// <summary>
/// Given a list of assemblies, find all types exposing the
/// <see cref="IocExportAssemblyAttribute"/> attribute
/// </summary>
/// <param name="assemblyPrefix">The prefix of the assembly names to load</param>
/// <returns>list of types exposing the <see cref="IocExportAssemblyAttribute"/> attribute</returns>
private static IEnumerable<Type> EnumerateIocBootstraperTypes(string assemblyPrefix)
{
var assemblies = EnumerateIocAssemblies(assemblyPrefix);
var iocInterface = typeof(IIocInstaller);
var bootstrapers = assemblies.SelectMany(s => s.GetTypes())
.Where(iocInterface.IsAssignableFrom);
return bootstrapers;
}
/// <summary>
/// Enumerate and return all assemblies whose name starts by "Eden.SMS"
/// </summary>
/// <returns><see cref="IEnumerable{T}"/>list of assemblies</returns>
/// <param name="assemblyPrefix">The prefix of the assembly names to load</param>
private static IEnumerable<Assembly> EnumerateIocAssemblies(string assemblyPrefix)
{
return from assembly in AppDomain.CurrentDomain.GetAssemblies()
where assembly.GetName().Name.StartsWith(assemblyPrefix)
select assembly;
}
}
and this is used in the Unity bootstrapper
/// <summary>
/// Dependency injection bootstrapper
/// </summary>
public static class Bootstrapper
{
private const string ASSEMBLY_PREFIX = "Eden.SMS";
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
AssemblyInjector.RegisterAssemblyTypes(container, ASSEMBLY_PREFIX);
//RegisterSatelliteTypes(container);
// Register local types
RegisterTypes(container);
foreach ( var registration in container.Registrations )
{
Debug.WriteLine(string.Format("Registered {0} as {1}", registration.RegisteredType, registration.MappedToType));
}
return container;
}
private static void RegisterSatelliteTypes(UnityContainer container)
{
new Eden.SMS.Data.Adapters.Mssql.Bootstrapper().Setup(container);
new Eden.SMS.Data.Managers.Bootstrapper().Setup(container);
new Eden.SMS.Service.Bootstrapper().Setup(container);
}
private static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IController, CustomersController>(new InjectionConstructor(typeof(ICustomerFacade)));
container.RegisterType<IController, AuthenticationController>(new InjectionConstructor(typeof(IAuthenticationFacade)));
}
}
The bootstrapper, in turns, is called from Application_Start() in Global.asax.
If in bootstrapper I comment this line
AssemblyInjector.RegisterAssemblyTypes(container, ASSEMBLY_PREFIX);
and uncomment this
RegisterSatelliteTypes(container);
it works as expected (no exception thrown after the app is unloaded by the web server).
That change disables the dynamic lookup of classes implementing the IIocInstaller, replacing that by direct calls on each satellite assembly.
This workaround fixes the bug, but I'd want to stick with the original "dynamic" plan. So I'd like to figure out why that is happening and how to solve it. Any suggestion?
I believe your issue is what this other post describes about the way DLLs are loaded into the AppDomain by the .Net Framework:
The .NET Framework defers loading assemblies into the current
AppDomain until they're needed. For example, if you call into a
third-party library only from SomeMethod(), the third-party DLL
normally won't be loaded until the first time SomeMethod() runs.
AppDomain.GetAssemblies() gives you all assemblies which have already
been loaded into the current AppDomain.
The good news are that there is method BuildManager.GetReferencedAssemblies() that returns a list of all assemblies referenced from Web.config and elsewhere, and it loads those assemblies into the current AppDomain.
This was the cause for this issue similar to yours, which was solved using BuildManager.GetReferencedAssemblies() instead of AppDomain.CurrentDomain.GetAssemblies().
Hope it helps!

WCF Read data issue from service

I am tying to get the generic List of user List<User> object from my web service to my web application. probably this is common issue. i searched a lot but got different remedies with each link. so finally i decide to ask to chaps over here... anyways
I am using console application for fetching the data from my hosted wcf web service. where as my WCf web service having the Entity framework 4.1. am using objects from its model class. when i tried to add service reference to my web application , it typically generates the proxy in web app. i am able to post data means i could create user. but while getusers which is returning List , getting following exceptions...:
Exception:
An error occurred while receiving the HTTP response to
http://myserver/AdminService/MyAdminService.svc. This could be due to
the service endpoint binding not using the HTTP protocol. This could
also be due to an HTTP request context being aborted by the server
(possibly due to the service shutting down). See server logs for more
details.
Inner Exception is :
The underlying connection was closed: An unexpected error occurred
on a receive
and inner-inner exception is : Unable to read data from the
transport connection: An existing connection was forcibly closed by
the remote host.
with message : An existing connection was forcibly closed by the
remote host
Error Code :10054
Where as Event log saying :
A message was not logged.
Exception: System.ServiceModel.CommunicationException: There was
an error while trying to serialize parameter
http://tempuri.org/:getUsersResult. The InnerException message was
'Type
'System.Data.Entity.DynamicProxies.User_00DEC686D7E21DB0D84B595F647A03FFB4943938F76E8C3DBBE0F77F8BC29A1D'
with data contract name
'User_00DEC686D7E21DB0D84B595F647A03FFB4943938F76E8C3DBBE0F77F8BC29A1D:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'
is not expected. Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.'. Please see
InnerException for more details. --->
System.Runtime.Serialization.SerializationException: Type
'System.Data.Entity.DynamicProxies.User_00DEC686D7E21DB0D84B595F647A03FFB4943938F76E8C3DBBE0F77F8BC29A1D'
with data contract name
'User_00DEC686D7E21DB0D84B595F647A03FFB4943938F76E8C3DBBE0F77F8BC29A1D:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'
is not expected. Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.
at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract
dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean
verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type
declaredType)
at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator
xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type
objectType, Int32 declaredTypeID, RuntimeTypeHandle
declaredTypeHandle, Type declaredType)
at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator
xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType,
Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator
xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType,
Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
at WriteArrayOfUserToXml(XmlWriterDelegator , Object ,
XmlObjectSerializerWriteContext , CollectionDataContract )
at
System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator
xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
at
System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator
writer, Object graph, DataContractResolver dataContractResolver)
at
System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator
writer, Object graph, DataContractResolver dataContractResolver)
at
System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator
writer, Object graph, DataContractResolver dataContractResolver)
at
System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter
writer, Object graph)
at
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter
writer, PartInfo part, Object graph)
--- End of inner exception stack trace ---
at
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter
writer, PartInfo part, Object graph)
at
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameter(XmlDictionaryWriter
writer, PartInfo part, Object graph)
at
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter
writer, MessageVersion version, String action, MessageDescription
messageDescription, Object returnValue, Object[] parameters, Boolean
isRequest)
at
System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter
writer)
at
System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter
writer)
at
System.ServiceModel.Channels.Message.ToString(XmlDictionaryWriter
writer)
at
System.ServiceModel.Diagnostics.MessageLogTraceRecord.WriteTo(XmlWriter
writer)
at
System.ServiceModel.Diagnostics.MessageLogger.LogInternal(MessageLogTraceRecord
record)
at
System.ServiceModel.Diagnostics.MessageLogger.LogMessageImpl(Message&
message, XmlReader reader, MessageLoggingSource source)
at
System.ServiceModel.Diagnostics.MessageLogger.LogMessage(Message&
message, XmlReader reader, MessageLoggingSource source)
Process Name: w3wp
Process ID: 5928
What should be this issue. me and team searching for this since 3 days. but unfortunately not overcome so far...
I tried lot of stuffs like add serializable attribute, endpoint modifications ... i can not recollect all :) ... probably you may give us right directions...
The reason is that EF classes are by default proxied at runtime to support lazy loading and dynamic change tracking. So you don't serialize User class but class derived from User at runtime. WCF doesn't like that. Turn off proxy creation on your context.
context.Configuration.ProxyCreationEnabled = false;

How to debug nHibernate/RhinoMocks TypeInitializer exception

Pulling my hair out trying to debug this one. Earlier this morning, this code was working fine, and I can't see what I've changed to break it. Now, whenever I try to open an nHibernate session, I'm getting the following error:
Test method BCMS.Tests.Repositories.BlogBlogRepositoryTests.can_get_recent_blog_posts threw exception: System.TypeInitializationException: The type initializer for 'NHibernate.Cfg.Environment' threw an exception. ---> System.Runtime.Serialization.SerializationException: Type is not resolved for member 'Castle.DynamicProxy.Serialization.ProxyObjectReference,Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f'..
Any thoughts on how to debug what's going on here?
I hit the same issue as you - in my case it was with NLog's static method:
LogManager.GetCurrentClassLogger()
I'd replaced the current thread's principal with a Rhinomocks stub:
var identity = MockRepository.GenerateStub<IIdentity>();
identity.Stub(x => x.IsAuthenticated).Return(true);
var principal = MockRepository.GenerateStub<IPrincipal>();
principal.Stub(x => x.Identity).Return(identity);
Thread.CurrentPrincipal = principal;
Running unit tests for my code threw the same exception from the original question.
The stack trace:
at System.AppDomain.get_Evidence()
at System.AppDomain.get_EvidenceNoDemand()
at System.AppDomain.get_Evidence()
at System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, String& typeName)
at System.Configuration.ClientConfigPaths.GetTypeAndHashSuffix(AppDomain appDomain, String exePath)
at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at NLog.Config.XmlLoggingConfiguration.get_AppConfig()
at NLog.LogFactory.get_Configuration()
at NLog.LogFactory.GetLogger(LoggerCacheKey cacheKey)
at NLog.LogFactory.GetLogger(String name)
at NLog.LogManager.GetCurrentClassLogger()
at MyClassHere...
So as you can see from the stack trace an attempt to read the config file is made, which won't work - why? Because the now mocked current principal is no longer the WindowsPrincipal that we had originally - it's now a mocked principal which won't have any sort of windows file access.
Thinking off the cuff here's a couple of ways to fix this issue.
Inject the logger into my class so that it can be stubbed (I probably should be doing this anyway I suppose..). This would allow me to use a stub for the Thread principal.
Modify the existing WindowsPrincipal (or create another based on it) on the thread to add in the roles required to call my methods.
-- UPDATE --
To fix my issue, in the end I decided to run with my first suggestion above. To avoid writing my own abstraction of the NLog Logger I just leveraged what was offered from Common.Logging. Class constructors now accept an ILog as one of their parameters, and the Unity config to inject the logger just looks like this:
container.RegisterType<ILog>(new TransientLifetimeManager(), new InjectionFactory(x => LogManager.GetCurrentClassLogger()));
Meanwhile, my unit tests now allow me to pass in a mocked logger.
var logger = MockRepository.GenerateStub<ILog>();
Some more info... it seems to be related to switching the Thread.CurrentPrincipal to a mocked IPrincipal implementation. I do all my security checks in my domain model inside the entities. The entity's methods check Thread.CurrentPrincipal.IsInRole() before modifying properties on the entity.
So, in order to test the entity's methods, I have to set different users (contributor user, moderator user, etc.) before I make my entity method calls.
I haven't figured out why this was working fine yesterday.
Here's an example of my Mocked IPrincipal:
private static IPrincipal _blogContributorUser = null;
public static IPrincipal BlogContributorUser
{
get
{
if (null == _blogContributorUser)
{
var identity = MockRepository.GenerateStub<IIdentity>();
identity.Stub(p => p.Name).Return("BlogContributor").Repeat.Any();
var principal = MockRepository.GenerateStub<IPrincipal>();
principal.Stub(p => p.Identity).Return(identity).Repeat.Any();
principal.Stub(p => p.IsInRole(UserRoles.BlogContributor)).Return(true).Repeat.Any();
principal.Stub(p => p.IsInRole(UserRoles.CommentContributor)).Return(true).Repeat.Any();
principal.Stub(p => p.IsInRole(UserRoles.TagContributor)).Return(true).Repeat.Any();
_blogContributorUser = principal;
}
return _blogContributorUser;
}
}
I have the same issue. It looks like that it has trouble reading the config file, since CurrentPrincipal is changed. I have moved all that has to be initialized from the config file, before replacing the CurrentPrincipal (for example, opened NHibernate session, initialized Unity and that kind of stuff), and everything works after that. Of course, this is not a solution, just a workaround figured out by a desperate man.
Errors like this usually indicate versioning issues.
What I suspect may be happening is that both RhinoMocks and NHibernate are making use of Castle.DynamicProxy type, but they are asking for different versions of that type.
Did you recently uprade RhinoMocks or NHibernate to a newer version?
If this isn't the issue, then more information would be helpful - do all tests fail, or just this particular one?
edit You may also wish to try adding these lines to your Properties\AssemblyInfo.cs file:
[assembly: InternalsVisibleTo("Rhino.Mocks")]
[assembly: InternalsVisibleTo("Castle.DynamicProxy")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
In case the error is related to mocking IPrincipal and/or IIdentity with RhinoMocks or Moq the solution is actually quite simple: don't use those frameworks but create simple fake types instead.
Here is an example for a simple "allow everything" implementation:
public class FakeIdentity : IIdentity
{
public string Name { get { return "IntegrationTest"; } }
public string AuthenticationType { get { return "Kerberos"; } }
public bool IsAuthenticated { get { return true; } }
}
public class FakePrincipal : IPrincipal
{
public FakePrincipal() { this.Identity = new FakeIdentity(); }
public IIdentity Identity { get; private set; }
public bool IsInRole(string role) { return true; }
}
If you need more complexity take a look at the System.Security.Principal.GenericPrincipal class.