System.BadImageFormatException: Bad binary signature. in Azure App Service - c#

I have made an ASP.NET Core (.Net 5) Web API which works perfectly fine on my local machine. And actually all contorllers except one work fine too. When I make a Post Request to my DataStoreController I get the following exception:
System.BadImageFormatException: Bad binary signature. (0x80131192)
at
System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(RuntimeMethodHandleInternal
method) at System.Reflection.Emit.DynamicMethod.CreateDelegate(Type
delegateType, Object target) at
System.Linq.Expressions.Compiler.LambdaCompiler.Compile(LambdaExpression
lambda) at System.Linq.Expressions.Expression`1.Compile() at
Microsoft.Extensions.Internal.ObjectMethodExecutor.GetExecutor(MethodInfo
methodInfo, TypeInfo targetTypeInfo) at
Microsoft.Extensions.Internal.ObjectMethodExecutor..ctor(MethodInfo
methodInfo, TypeInfo targetTypeInfo, Object[] parameterDefaultValues)
at
Microsoft.Extensions.Internal.ObjectMethodExecutor.Create(MethodInfo
methodInfo, TypeInfo targetTypeInfo, Object[] parameterDefaultValues)
at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvokerCache.GetCachedResult(ControllerContext
controllerContext) at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvokerProvider.OnProvidersExecuting(ActionInvokerProviderContext
context) at
Microsoft.AspNetCore.Mvc.Infrastructure.ActionInvokerFactory.CreateInvoker(ActionContext
actionContext) at
Microsoft.AspNetCore.Mvc.Routing.ActionEndpointFactory.<>c__DisplayClass7_0.b__0(HttpContext
context) at
Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext
httpContext)
--- End of stack trace from previous location --- at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext
httpContext) at
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext
httpContext, ISwaggerProvider swaggerProvider) at
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext
context)
I have tried what would happen if I made the Method inside the Controller empty and just return null - but still the same error. The only differnce package-wise to the other controllers is that the DataStoreController uses the Stackexchange.Redis NuGet Package.
My gut feeling tells me that this is a weird Azure Bug, but I would love to get some opinions/advices/answers from you.

Okay okay. I have kind of found a solution.
I stopped and started the App Service and now everything works. This actually might be a weird Azure Issue.

Related

Setting HttpRuntime.WebObjectActivator makes HttpApplication.InitModulesCommon throw a NullReferenceException

Setting HttpRuntime.WebObjectActivator makes HttpApplication.InitModulesCommon throw a NullReferenceException.
I'm setting it in my Application_Start and setting it back to null makes the error go away so its consistent.
The stacktrace is as follows
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.HttpApplication.InitModulesCommon() +166
System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +792
System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +153
System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +107
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +327
My best guess is that its this line which is failing https://referencesource.microsoft.com/#system.web/HttpApplication.cs,2337 due to all modules being resolved by the WebObjectActivator and therefor returning null if they arent registered as seen here https://referencesource.microsoft.com/#system.web/ModulesEntry.cs,62 and here https://referencesource.microsoft.com/#system.web/HttpRuntime.cs,3388
By is that really the case... ? Is it really the responsibility of the activator to instantiate objects which isn't registered as well?
Reading the answer to this question unfortunately confirms that whoever cooked up HttpRuntime.WebObjectActivator wasn't thinking it through
Wiring up Simple Injector in WebForms in .NET 4.7.2

Hangfire + SimpleInjector + MVC

I’m trying to setup Hangfire for our MVC app. I followed all tutorials, used Devmondo HangFire.SimpleInjector for activator logic but still have issues.
My startup setup is as following:
//Hangfire
Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage(webClientConfigurationService.DataConnectionStringName);
Hangfire.GlobalConfiguration.Configuration.UseActivator(new SimpleInjectorJobActivator(Core.Dependencies.DependencyResolver.Container));
app.UseHangfireDashboard();
app.UseHangfireServer();
//add hangfire test job
var _selfAccreditationsService = Core.Dependencies.DependencyResolver.Resolve<ISelfAccreditationsService>();
RecurringJob.AddOrUpdate(() => _selfAccreditationsService.TestHangFire(), Cron.MinuteInterval(1));
Application starts fine but when I go to dasboard I can see:
System.TypeLoadException: Could not load type ‘SimpleInjector.Lifestyles.AsyncScopedLifestyle’ from assembly ‘SimpleInjector, Version=3.1.2.0, Culture=neutral, PublicKeyToken=984cb50dea722e99’.
at Hangfire.SimpleInjector.SimpleInjectorJobActivator.BeginScope(JobActivatorContext context)
at Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext context)
at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass8_0.b__0()
at Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter filter, PerformingContext preContext, Func1 continuation) at Hangfire.Server.BackgroundJobPerformer.PerformJobWithFilters(PerformContext context, IEnumerable1 filters)
at Hangfire.Server.BackgroundJobPerformer.Perform(PerformContext context)
at Hangfire.Server.Worker.PerformJob(BackgroundProcessContext context, IStorageConnection connection, String jobId)
EDIT: Even with fresh MVC template project after adding all of above it’s still giving me same error :frowning:
Do you guys have any ideas what I have missed? Would really appreciate any help with this.
Thanks

LightInject Attempt to create a scoped instance without a current scope

I (noob to light inject mvc) am using LightInject MVC in my asp.mvc 4 app with great results except an occasional exception. Now I am seeing it in pre-production. The exception is: System.InvalidOperationException: Attempt to create a scoped instance without a current scope.
My app start code is:
var container = new LightInject.ServiceContainer();
container.RegisterControllers();
container.RegisterAssembly(typeof(AppDDD.RegisterMe).Assembly, () => new PerScopeLifetime());
... scoped registrations
container.EnableMvc();
I get the error with a stack trace like:
System.InvalidOperationException: An error occurred when trying to
create a controller of type 'MvcAPP.Controllers.HomeController'. Make
sure that the controller has a parameterless public constructor. --->
System.InvalidOperationException: Attempt to create a scoped instance
without a current scope. at
LightInject.PerScopeLifetime.GetInstance(Func1 createInstance, Scope
scope) at DynamicMethod(Object[] ) at
LightInject.ServiceContainer.<>c__DisplayClass40.<WrapAsFuncDelegate>b__3f()
at LightInject.PerRequestLifeTime.GetInstance(Func1 createInstance,
Scope scope) at DynamicMethod(Object[] ) at
LightInject.ServiceContainer.TryGetInstance(Type serviceType) at
System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) --- End of inner exception
stack trace --- at
System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(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)
I have created a couple of small test ASP MVC projects to isolate the exception with no success.
The Controllers are scoped per instance, and all the objects with in each instance are designated PerScopeLifetime.
Is there a tweak I can make, or should I stop using PerScopeLifetime? I must have scoped lifetimes for my EF contexts.
The exception is thrown before my controllers finish constructing, so it appears.
I would like you to know that the issue has been resolved and getting the latest and greatest from NuGet should fix your problem.
Best regards
Bernhard Richter

Response is not available in this context

I have problem. Locally everything works fine but in the production server it always throws exception 'Response is not available in this context'. What can be the problem? I've noticed that a lot of people experience this problem due to some changes of global.asax. Here is the code of global.asax, the part related to application start.
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
Application["SystemUser"] = TUser.GetUserByIdentifier("system").UID;
InitializeSolrInstances();
SearchIndexer.DoIndex();
StartRatingTimer();
SolrManager.RecalculateMostRequested();
}
private static void InitializeSolrInstances() {
SolrConfigurationManager.InitSolrConnection<OfferItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/offer");
SolrConfigurationManager.InitSolrConnection<SavedQueryItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/savedquery");
SolrConfigurationManager.InitSolrConnection<TopProductsPresenter>(Resources.ApplicationResources.SolrServiceURL + "/topproducts");
SolrConfigurationManager.InitSolrConnection<TopSellersPresenter>(Resources.ApplicationResources.SolrServiceURL + "/topsellers");
SolrConfigurationManager.InitSolrConnection<MostRequestedItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/mostrequested");
SolrConfigurationManager.InitSolrConnection<MostRequestedQuery>(Resources.ApplicationResources.SolrServiceURL + "/requestedquery");
}
private void StartRatingTimer() {
_LastRatingRenewedTime = DateTime.Now;
DateTime CurrentTime = DateTime.Now;
DateTime StartTime = new DateTime(2011, 1, 1);
GlobalSettings.ReIndexMainSolrCores(StartTime, CurrentTime);
Timer OfferAndUserRatingRenewerTimer = new Timer() {
/*Timer interval for 24 hours*/
Interval = 24 * 60 * 60 * 1000, Enabled = true };
OfferAndUserRatingRenewerTimer.Elapsed += new ElapsedEventHandler(OfferAndUserRatingRenewerTimer_Elapsed);
}
public void OfferAndUserRatingRenewerTimer_Elapsed(Object Sender, ElapsedEventArgs e) {
GlobalSettings.ReIndexMainSolrCores(_LastRatingRenewedTime, e.SignalTime);
_LastRatingRenewedTime = e.SignalTime;
}
I do not use Response or Request properties of HttpContext at all. Neither in global asax itself, nor within the methods to be called. Help me.
That what it shows.
`
Server Error in '/' Application.
Response is not available in this context.
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.Web.HttpException: Response is not available in this context.
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:
[HttpException (0x80004005): Response is not available in this context.]
System.Web.Util.HttpEncoder.get_Current() +11406684
System.Web.HttpUtility.UrlEncode(String str, Encoding e) +137
SolrNet.Impl.SolrConnection.<Get>b__0(KeyValuePair`2 input) +89
SolrNet.Utils.<Select>d__1a`2.MoveNext() +612
SolrNet.Utils.Func.Reduce(IEnumerable`1 source, TResult startValue, Accumulator`2 accumulator) +393
SolrNet.Impl.SolrConnection.Get(String relativeUrl, IEnumerable`1 parameters) +908
SolrNet.Impl.SolrQueryExecuter`1.Execute(ISolrQuery q, QueryOptions options) +195
SolrNet.Impl.SolrBasicServer`1.Query(ISolrQuery query, QueryOptions options) +176
SolrNet.Impl.SolrServer`1.Query(ISolrQuery query, QueryOptions options) +176
TebeComSearchEngine.SolrManager.RecalculateMostRequested() in SolrManager.cs:77
TebeCom.MvcApplication.Application_Start() in Global.asax.cs:101
[HttpException (0x80004005): Response is not available in this context.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +4043621
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +191
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +352
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +407
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +375
[HttpException (0x80004005): Response is not available in this context.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11612256
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +141
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4842149`
'Response is not available in this context'. What can be the problem?
You are running this in IIS7 Integrated Application Pool mode instead of Classic mode. In Integrated mode you don't have access to the HttpResponse in Application_Start any any attempt to access it will blow.
Here's a blog post which covers a similar situation but with the HttpRequest.
After a lot of digging and looking around the SolrNet code, they don't appear to be doing anything wrong. Also, as Darin pointed out in an indirect manner, HttpUtility.UrlEncode should work fine in code without a HttpContext, such as a console application, and it does.
However, as VinayC pointed out in his comment on that answer of Darin's:
Actually, it appears to be a bug. From
reflector, actual code appears to be
"if (null != current && null !=
current.Response && ...)" where
current is current http context. Issue
here is that Response getter throws an
exception, instead of returning null
Instead of throwing that overly descriptive exception (no doubt they were trying to be helpful), they should have just returned null and let null reference exceptions happen. In this case, they were simply checking for nulls, so the exception wouldn't have happened anyway! I'll report it as a bug if it hasn't been already.
Unfortunately, what this means to you is that you have pretty much no choice but to run in Classic mode. Technically you could put the call to TebeComSearchEngine.SolrManager.RecalculateMostRequested() in a thread that you spawn in application_start and delay its execution until after the app finishes starting. As far as I know, there is no surefire way to programmatically signal the end of the application starting so, that approach may be a little messy.
If you're up for it though, you could probably get that delayed startup mechanism implemented. Compared to punishing the first visitor to the site, it doesn't seem too bad.
This was discussed about a month ago in the SolrNet mailing list.
It's a regression in ASP.NET 4, here's a mention of this bug.
A future release of SolrNet will replace System.Web.HttpUtility.UrlEncode to work around this bug. (or if you really need this, why not fork the source code and fix it?)
EDIT: I just fixed this.

A Cause for HRESULT 0X80131468 when accessing IsolatedStorageBackingStore

The scenario I am facing is that I have an ASP.NET web service (.NET 3.5) running on an W2k3 server which is using the CacheManager/IsolatedStorage store to store a persisted state variable. This configuration has been working fine for quite sometime until we changed the physical machine. Now whenver the code that accesses that value runs it throws an IsolatedStorageException (Posted below). As I understand it the user/assembly store is what is being accessed and the executing user is a member of the local administrators group. Does anyone have a suggestion as to what privilege is missing?
Error
Unable to create the store directory. (Exception from HRESULT: 0x80131468)
Stack Trace
Type: Microsoft.Practices.ObjectBuilder2.BuildFailedException. Error: The current build operation (build key Build Key[Microsoft.Practices.EnterpriseLibrary.Caching.ICacheManager, Cache Manager]) failed: Unable to create the store directory. (Exception from HRESULT: 0x80131468) (Strategy type ConfiguredObjectStrategy, index 2). Trace: at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.Builder.BuildUp(IReadWriteLocator locator, ILifetimeContainer lifetime, IPolicyList policies, IStrategyChain strategies, Object buildKey, Object existing)
at Microsoft.Practices.ObjectBuilder2.Builder.BuildUp[TTypeToBuild](IReadWriteLocator locator, ILifetimeContainer lifetime, IPolicyList policies, IStrategyChain strategies, Object buildKey, Object existing)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.EnterpriseLibraryFactory.BuildUp[T](IReadWriteLocator locator, ILifetimeContainer lifetimeContainer, IConfigurationSource configurationSource)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.LocatorNameTypeFactoryBase1.CreateDefault()
at Microsoft.Practices.EnterpriseLibrary.Caching.CacheFactory.GetCacheManager()
at Ept.Commands.SettlementCommand.BeginSettlement() in c:\Projects\EPT\Ept.Framework.Services\Commands\SettlementCommand.cs:line 102
at Ept.Commands.SettlementCommand.ExecuteKernel(SettlementRequest request) in c:\Projects\EPT\Ept.Framework.Services\Commands\SettlementCommand.cs:line 188
at Ept.Command2.Execute(TRequest request) in c:\Projects\EPT\Ept.Framework.Services\Commands\Command.cs:line 79. ExecutingStrategyTypeName: ConfiguredObjectStrategy ExecutingStrategyIndex: 2 BuildKey: Build Key[Microsoft.Practices.EnterpriseLibrary.Caching.ICacheManager, Cache Manager] Type: System.IO.IsolatedStorage.IsolatedStorageException. Error: Unable to create the store directory. (Exception from HRESULT: 0x80131468). Trace: at System.IO.IsolatedStorage.IsolatedStorageFile.nGetRootDir(IsolatedStorageScope scope)
at System.IO.IsolatedStorage.IsolatedStorageFile.InitGlobalsNonRoamingUser(IsolatedStorageScope scope)
at System.IO.IsolatedStorage.IsolatedStorageFile.GetRootDir(IsolatedStorageScope scope)
at System.IO.IsolatedStorage.IsolatedStorageFile.GetGlobalFileIOPerm(IsolatedStorageScope scope)
at System.IO.IsolatedStorage.IsolatedStorageFile.Init(IsolatedStorageScope scope)
at System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType)
at Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.IsolatedStorageBackingStore.Initialize()
at Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.IsolatedStorageBackingStore..ctor(String storageAreaName, IStorageEncryptionProvider encryptionProvider)
at Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.IsolatedStorageBackingStoreAssembler.Assemble(IBuilderContext context, CacheStorageData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.AssemblerBasedObjectFactory2.Create(IBuilderContext context, TConfiguration objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.AssemblerBasedCustomFactory2.Create(IBuilderContext context, String name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerAssembler.Assemble(IBuilderContext context, CacheManagerDataBase objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.AssemblerBasedObjectFactory2.Create(IBuilderContext context, TConfiguration objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Caching.CacheManagerCustomFactory.Create(IBuilderContext context, CacheManagerDataBase objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.AssemblerBasedCustomFactory2.Create(IBuilderContext context, String name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.AssemblerBasedCustomFactory`2.CreateObject(IBuilderContext context, String name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.ConfiguredObjectStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context).
The root cause of the issue is that the account which the web service was running under did not have a local user profile created thus the user assembly store didn't exist. The simple fix was just to logon to the box with the service account.
If you are using Windows 2012 R2 and IIS 8.5, in the case your App is running on a specific Application Pool under its own identity, you need to check that the option "Load user Profile" in the Pool Advanced Parameters is set to True.
By doing so, Windows will create a folder having App Pool Identity name under C:\Users and allow your app to write inside the local storage.
I had this issue but creating "C:\Documents and Settings\Default User\Local Settings\Application Data\IsolatedStorage" did not resolve the problem because at some point there was a profile name change. The actual location for this server was "C:\Documents and Settings\Default User.WINDOWS\Local Settings\Application Data\IsolatedStorage".
If that does not work, I used Process Monitor with a filter for "IsolatedStorage" to find the correct path for the access denied error.
On Windows 10 IIS Application Pool setting "Load User Profile" is True by default. But on Windows 2012 is False. Switching to True solved my issue.

Categories