Getting Null reference/ HandleEntityAppendOnly error while eager loading - entity-framework-5

The solution to this nut seems to elude me :-)
We have a method that eager loads some related entities and this works fine when it is hosted in a local IIS-instance on our development machines (Windows 7 Enterprise, 64-bitSP1, VS2012SP3 with solution built against Net 4.5)
However, when we run it hosted in IIS on a server (Windows 2008 R2 Standard SP1) it fails with the following error:
2013-09-27 08:42:09,950 ERROR#27[rastructrure.Repositories.SäkerhetsorderRepository] Fel i SäkerhetsorderRepository.AllMatching()
System.NullReferenceException: Object reference not set to an instance of an object.
at log4net.LogManager.GetLogger(Type type)
at Kororder.Domain.Aggregat.Säkerhetsorder.Säkerhetsorder..ctor()
at lambda_method(Closure , Shaper )
at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
at lambda_method(Closure , Shaper )
at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Kororder.Infrastructrure.Repositories.SäkerhetsorderRepository.AllMatching(ISpecification`1 specification)
Any ideas?
UPDATE, I forgot the topmost line in the error that we log

Read the error message, you are using log4net and the LogManager instance seems to be null. Might be a configuration issue because usually you define your log4net configuration within the web.config

Related

ASP.NET application (always running) shuts down application pool when publishing

I've followed this guide here: Making ASP.NET application always running
However when I publish my web application to IIS 8.5 it shuts down the application pool and my event viewer shows the following message:
There was an error during processing of the managed application service
auto-start for configuration path:
'MACHINE/WEBROOT/APPHOST/mydomain.co.uk/'. The error message returned is:
'An initialization error occurred while trying to preload an application.
Exception: System.InvalidOperationException
Message: Well known object of type 'System.Web.Hosting.PreloadHost' already
exists in this App Domain.
StackTrace: at
System.Web.Hosting.HostingEnvironment.CreateWellKnownObjectInstance(String
assemblyQualifiedName, Boolean failIfExists)
at
System.Web.Hosting.HostingEnvironment.CreateWellKnownObjectInstance(String
assemblyQualifiedName, Boolean failIfExists)
at System.Web.Hosting.ApplicationManager.CreateObjectInternal(String appId,
Type type, IApplicationHost appHost, Boolean failIfExists,
HostingEnvironmentParameters hostingParameters)
at System.Web.Hosting.ProcessHost.PreloadApplicationIfRequired(String appId,
IApplicationHost appHostParameter, HostingEnvironmentParameters
hostingParameters, LockableAppDomainContext ac)
at System.Web.Hosting.ProcessHost.<>c__DisplayClass38_0.
<PreloadApplicationIfNotShuttingdown>b__0(Object o)'. The worker process will
be marked unhealthy and be shutdown. The data field contains the error code.
I can't for the life of me resolve this, or figure out where to start debugging it. If I manually start the application pool afterwards everything works fine -
it's just an annoyance really. Any advice appreciated.
Ahhhh. I've found the solution (well...it worked for me anyhow). And it was down to this great article: https://weblog.west-wind.com/posts/2013/oct/02/use-iis-application-initialization-for-keeping-aspnet-apps-alive
In particular, and what wasn't mentioned in the Hangfire tutorial above, was the need to:
Add the 'Applicaiton Initialization' role. On IIS 8.5 it was in a slightly different place to the linked article. It is in: Web Server (IIS) > Web Server > Application Development > Application Initialization
Also I needed to make sure that the 'Preload Enabled' flag was set, of which it wasn't. For that I highlighted my site in IIS, clicked 'Advanced Settings' in the right-hand panel, and set it there.
I then tried to publish my site again and voila....no HTTP Error 503!
UPDATE
This isn't the solution. The only reason it worked is because I'd attached the debugger (DebugDiag) and that seems to make it work for some reason! As soon as I detached the debugger I get the same error.
The selected answer helped me. If anyone else is having additional trouble, turned out I also didn't have the correct version of .NET installed on my machine; my app targeted 4.7, and the latest I had was 4.5. Once I got that installed, everything worked fine.
I increased the rapid fail protection maximum failures on the app pool to around 20. I'm not sure if this is the best way to solve it though.
IIS Manager
Application Pools
Select app pool
Advanced Settings
Scroll down to Rapid-Fail Protection
Maximum Failures - I changed this to 20
OK

Profile Base GetProfile command throws null type in CreateInstance

I am working on a web application that uses built-in security classes to create new users
newuser = MembershipUser.Create(relevant parameters)
that is all well and good
it then issues a Profile.GetProfile(newuser.UserName)
which drills down to a
System.Activator.CreateInstance(Type type, Boolean nonPublic)
which throws a
Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: type
it works fine in dev (visual Studio 2015 Community)
the current site was developed on an older machine, probably Visual Studio 2010
and works just fine
why am I getting these errors - and how do I fix it?

Azure Redis Cache StackExchange.Redis.RedisConnectionException: No connection is available to service this operation: EVAL

Asp.net mvc 5 application web config file is
sessionState mode="Custom" customProvider="RedisSessionProvider">
providers>
add name="RedisSessionProvider" type="Microsoft.Web.Redis.RedisSessionStateProvider" port="6380" host="XXX.redis.cache.windows.net" accessKey="XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ssl="true" />
providers>
sessionState>
When i run application have eror
Server Error in '/' Application.
No connection is available to service this operation: EVAL
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: StackExchange.Redis.RedisConnectionException: No connection is available to service this operation: EVAL
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:
[RedisConnectionException: No connection is available to service this operation: EVAL]
StackExchange.Redis.ConnectionMultiplexer.ExecuteSyncImpl(Message message, ResultProcessor`1 processor, ServerEndPoint server) in c:\TeamCity\buildAgent\work\3ae0647004edff78\StackExchange.Redis\StackExchange\Redis\ConnectionMultiplexer.cs:1922
StackExchange.Redis.RedisBase.ExecuteSync(Message message, ResultProcessor`1 processor, ServerEndPoint server) in c:\TeamCity\buildAgent\work\3ae0647004edff78\StackExchange.Redis\StackExchange\Redis\RedisBase.cs:80
StackExchange.Redis.RedisDatabase.ScriptEvaluate(String script, RedisKey[] keys, RedisValue[] values, CommandFlags flags) in c:\TeamCity\buildAgent\work\3ae0647004edff78\StackExchange.Redis\StackExchange\Redis\RedisDatabase.cs:866
Microsoft.Web.Redis.<>c__DisplayClass4.<Eval>b__3() in c:\TeamCity\buildAgent\work\f55792526e6d9089\src\Shared\StackExchangeClientConnection.cs:113
Microsoft.Web.Redis.StackExchangeClientConnection.RetryForScriptNotFound(Func`1 redisOperation) in c:\TeamCity\buildAgent\work\f55792526e6d9089\src\Shared\StackExchangeClientConnection.cs:129
Microsoft.Web.Redis.StackExchangeClientConnection.RetryLogic(Func`1 redisOperation) in c:\TeamCity\buildAgent\work\f55792526e6d9089\src\Shared\StackExchangeClientConnection.cs:155
Microsoft.Web.Redis.StackExchangeClientConnection.Eval(String script, String[] keyArgs, Object[] valueArgs) in c:\TeamCity\buildAgent\work\f55792526e6d9089\src\Shared\StackExchangeClientConnection.cs:113
Microsoft.Web.Redis.RedisConnectionWrapper.Set(ISessionStateItemCollection data, Int32 sessionTimeout) in c:\TeamCity\buildAgent\work\f55792526e6d9089\src\RedisSessionStateProvider\RedisConnectionWrapper.cs:135
Microsoft.Web.Redis.RedisSessionStateProvider.SetAndReleaseItemExclusive(HttpContext context, String id, SessionStateStoreData item, Object lockId, Boolean newItem) in c:\TeamCity\buildAgent\work\f55792526e6d9089\src\RedisSessionStateProvider\RedisSessionStateProvider.cs:408
System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs) +906
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +142
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +92
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1055.0
I had the same, and eventually fixed it by adding sslprotocols=tls12 to the connectionstring. It should not be necessary, but apparently it is, using recently created Redis caches on Azure. Probably due to the deprecation of TLS 1.0 and 1.2
Could be for 3 reasons:
Your connection string is wrong (looks ok any way)
The instance isn't yet created (usually takes a lot to be created in azure)
You are facing firewall (including windows firewall) issues
Are you able to get connected to the redis cache instance using command prompt?
Download redis for windows Here
and then run
redis-cli -h XXX.redis.cache.windows.net -a XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
You can find here a detailed demo (in spanish but console demos remains usable.)
NinjaTip #18 - Introducción a Redis
For testing purposes ensure than Redis service has port 6379 open (this is the non SSl port option you need to enable on azure)
If you can't connect to your instance is because some of the reasons listed above.
I had the same issue before and I found a solution that using another one:
https://github.com/alex-simonov/RedisAspNetProviders
This one works for me
I found that only the following configuration in web config works for me:
<sessionState mode="Custom" customProvider="MySessionStateStore">
<providers>
<add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" connectionString="PUTCORRECTNAMEHERE.edis.cache.windows.net:6380,password=YOURPRIMARYKEYPUTHERE,ssl=True,abortConnect=False" />
</providers>
</sessionState>

Exception when running Azure Cloud Project

I have created an azure cloud project in visual studio.
1) Used the "Convert to Azure" feature.
2) Added a Https endpoint and certificate.
Attempting to run the project with the azure emulator locally "without debug" the emulator hangs. If I run the project with debugging it seems to start but i get the following exception:
A first chance exception of type 'System.ServiceModel.FaultException`1' occurred in System.ServiceModel.dll
Additional information: Invalid name.
Parameter name: name
After the exception sites fails to continue.
I was wondering if anyone has experienced this issue and how they resolved it?
Additional Information:
.net 4.5.1 framework.
IIS: version 7.5
Azure SDK 2.6
So looking into the WaIISHost.Log I have found the following exception which keeps being thrown:
WaIISHost Information: 0 : [00014196:00000001, 2015/07/15 07:45:38.428,ERROR] Exception:System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDeta il]: Invalid name.
Parameter name: name (Fault Detail is equal to An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.ArgumentException: Invalid name.
Parameter name: name
at System.Security.AccessControl.NativeObjectSecurity.CreateInternal(ResourceType resourceType, Boolean isContainer, String name, SafeHandle handle, AccessControlSections includeSections, Boolean createByName, ExceptionFromErrorCode exceptionFromErrorCode, Object exceptionContext)
at System.Security.AccessControl.FileSystemSecurity..ctor(Boolean isContainer, String name, AccessControlSections includeSections, Boolean isDirectory)
at System.Security.AccessControl.DirectorySecurity..ctor(String name, AccessControlSections includeSections)
at System.IO.DirectoryInfo.GetAccessControl(AccessControlSections includeSections)
at Microsoft.WindowsAzure.ServiceRuntime.IISConfigurator.FileManager.AddAllowAceIte rative(DirectoryInfo dir, FileSystemRights rights, IdentityReference[] accounts)
at Microsoft.WindowsAzure.ServiceRuntime.IISConfigurato...).
I found a solution to my issue in the end.
I'll be completely honest, i'm not entirely sure if its due to long path names as suggested by #spender or if its something else. I had a folder on my C drive called Dev:
C:\Dev\AzureSolutionExample\Source
I basically moved it directly onto the C drive and everything started working.
C:\AzureSolutionExample\Source

Unable to Install NServiceBus Host Windows Service

I'm attempting to follow the instructions to install the windows service host using NServiceBus.Host.exe for the VideoStore sample app. I'm following the instructions from the web site.
My application runs fine when doing an F5 session in Visual Studio. It's hosting using the console app mode for the host. When I attempt to use the command line to perform the installation, I get multiple errors.
The command line I'm running is:
NServiceBus.Host.exe /install /serviceName:"VideoStore.Sales"
/displayName:"VideoStore.Sales" /description:"Endpoint for
VideoStore.Sales"
/endpointConfigurationType:"VideoStore.Sales.EndpointConfig,
VideoStore.Sales" /username:".\MySvc" /password:"MyPassword"
NServiceBus.Production
Running this resulted in the following exception:
Initializing the installer in the Install AppDomain
Unhandled Exception: System.InvalidOperationException: Sequence
contains more than one matching element at
System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source,
Func2 predicate) at
System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext() at
System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext() at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at
NServiceBus.Hosting.Profiles.ProfileManager..ctor(List1
assembliesToScan, IConfigureThisEndpoint specifier, String[] args,
List`1 defaultProfiles)
It turns out, this error is caused because my application is referencing both the NServiceBus.Host assembly as well as the NServiceBus.Hosting.Azure assembly. This is because my application is being deployed both in a Windows environment as well as to an Azure worker role. I can switch between the azure emulator and the console-mode for worker roles without issue simply by changing which projects i'm starting when debugging. (Azure cloud service project vs each of the worker projects.)
I was able to resolve this by deleting the NServiceBus.Hosting.Azure.dll assembly to prevent the assembly scanning from finding it. IMHO, this is a bug. Either allow me to specify the host type explicitly or handle a scenario where multiple types are found.
This stopped the previous exception, and instead introduced a new one:
Unhandled Exception:
System.Configuration.ConfigurationErrorsException: Command line
argument 'endpointConfigurationType' has specified to use the type
'VideoStore.Sales.EndpointConfig, VideoStore.Sales' but that type
could not be loaded. at
NServiceBus.Hosting.Windows.EndpointTypeDeterminer.TryGetEndpointConfigurationTypeFromArguments(HostArguments
arguments, Type& type) in y:\BuildAgent\work
\31f8c64a6e8a2d7c\src\NServiceBus.Hosting.Windows\EndpointTypeDeterminer.cs:line
101 at NServiceBus.Hosting.Windows.Program.Main(String[] args) in
y:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceBus.Hosting.Windows\Program.cs:line
38
Both that type and that assembly exist. I've even verified that .NET is loading the type via enabling fusion loader logging:
The operation was successful. Bind result: hr = 0x0. The operation
completed successfully.
Assembly manager loaded from:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll Running under
executable
C:\Projects\Testing\NServiceBus.Azure.Samples-master\VideoStore.AzureServiceBus.Cloud\VideoStore.Sales\bin\Debug\NServiceBus.Host.exe
--- A detailed error log follows.
=== Pre-bind state information === LOG: DisplayName = VideoStore.Sales (Partial) WRN: Partial binding information was supplied for an
assembly: WRN: Assembly Name: VideoStore.Sales | Domain ID: 1 WRN: A
partial bind occurs when only part of the assembly display name is
provided. WRN: This might result in the binder loading an incorrect
assembly. WRN: It is recommended to provide a fully specified textual
identity for the assembly, WRN: that consists of the simple name,
version, culture, and public key token. WRN: See whitepaper
http://go.microsoft.com/fwlink/?LinkId=109270 for more information and
common solutions to this issue. LOG: Appbase =
file:///C:/Projects/Testing/NServiceBus.Azure.Samples-master/VideoStore.AzureServiceBus.Cloud/VideoStore.Sales/bin/Debug/
LOG: Initial PrivatePath = NULL LOG: Dynamic Base = NULL LOG: Cache
Base = NULL LOG: AppName = NServiceBus.Host.exe Calling assembly :
NServiceBus.Host, Version=4.6.0.0, Culture=neutral,
PublicKeyToken=9fc386479f8a226c.
What am I doing wrong here?
EDIT
I believe I see the issue. Basically, trying to avoid the first error where NServiceBus is resolving multiple Profiles due to the fact it's finding them in both NServiceBus.Core and NServicebus.Hosting.Azure is causing the second error.
This is because in order to load my EndpointConfig type, .NET also needs to load the NServicebus.Hosting.Azure assembly, as it implements AsA_Worker, which lives in NServiceBus.Hosting.Azure.
So be deleting that assembly, I'm preventing it from loading the EndpointConfig.
I'm still unclear as to how to resolve this. I need to get NServiceBus to stop scanning both hosting assemblies. This suggests that christof13's answer is correct, but I'm unable to get NServiceBus to ignore its own assemblies.
The root cause of this issue is that when NServiceBus enumerates profiles available, it scans all available assemblies and then does a LINQ statement to filter them down by type name.
The problem is that there are two NServiceBus.Production profiles, one defined in the NServiceBus.Host.dll, and one in the NServiceBus.Hosting.Azure assembly. Their type names are identical, and so the LINQ SingleOrDefault fails.
The suggestion to filter the assemblies searched wouldn't work because NServiceBus always loads its own assemblies. The filter only applies to my project's assemblies.
I was able to resolve this by creating a custom profile that doesn't have the same name as any other profile defined in any assemblies in my project. Something like:
public class DualCloudLocalProfile : IProfile {}
public class DualCloudLocalProfileHandler : IHandleProfile<DualCloudLocalProfile>
{
public void ProfileActivated()
{
if (LogManager.LoggerFactory is NullLoggerFactory || LogManager.LoggerFactory == null)
{
Configure.Instance.TraceLogger().ConsoleLogger();
}
}
}
public class CloudProfileLoggingHandler : IConfigureLoggingForProfile<DualCloudLocalProfile>
{
public void Configure(IConfigureThisEndpoint specifier)
{
//nothing for now
}
}
Once this was added into my project, I modified the install command to specify the new profile:
NServiceBus.Host.exe /install /serviceName:"VideoStore.Sales" /displayName:"VideoStore.Sales" /description:"Endpoint for VideoStore.Sales" /endpointConfigurationType:"VideoStore.Sales.EndpointConfig, VideoStore.Sales" /username:".\MySvc" /password:"MyPassword" VideoStore.Sales.DualCloudLocalProfile
This resolved the problem. I can now run the project as a cloud service and a NServiceBus.Host.exe hosted service, as well as deploy via the /install command for the host.
You can try to filter the assemblies with one the following methods
Configure.With(string probeDirectory)
Configure.With(params Assembly[] assemblies)
Configure.With(IEnumerable<Type> typesToScan)
By default I think that nservicebus scans all the assemblies in the folder, so if you filter with only the needed assemblies it will prevent from receiving this kind of error
http://docs.particular.net/nservicebus/the-nservicebus-host

Resources